0

I have a json data file from which I need to fetch only the id attribute value into a separate list variable. I tried for loop but not able to get the required data using terraform. Can someone tell how to fetch the id part ? your help is much appreacited.

code:

    locals {
    data = jsondecode(file("./data.json"))[*]
    sections = [ for item in local.data : item ]
}

output "ids" {
    value = [for a in local.sections[0]: a]
}

json file:

{
"c":[
   {
      "id":"6",
      "key":"c",
      "name":"s01"
   }
],
"l":{
   "id":"7",
   "key":"l",
   "name":"s02"
},
"m":{
   "id":"8",
   "key":"mp",
   "name":"s03"
},
"n":{
   "id":"5",
   "key":"cn",
   "name":"s04"
},
"od":"odk",
"s":{
   "id":"9",
   "key":"cs",
   "name":"s05"
},
"ss":{
   "id":"1",
   "key":"ss",
   "name":"s06"
},
"in":{
   "id":"65",
   "key":"cn",
   "name":"s07"
},
"b":{
   "id":"2",
   "key":"cb",
   "name":"s08"
}

}

2
  • 1
    What's wrong with your current code? Any errors? Commented Jun 15, 2022 at 10:32
  • @marcin, No error, it just output full json data but am trying to fetch only id attribute value Commented Jun 15, 2022 at 12:39

1 Answer 1

2

Not sure if "od":"odk", is mistake or not, but you can do the following:

locals {
    data = jsondecode(file("./data.json"))
}

output "ids" {
    value = [for v in values(local.data): v.id if can(v.id)]
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @Marcin. learned new stuff in terraform. Many Thanks
@vrledu No problem. Glad the answer was useful.
Applogise, I just noticed that from the solution you have provided is going to miss the first items/attribute id ie, id =6 since its list of dict. how can we get all the items id including first one ?
not sure if you had a chance to see my above message. any idea how can we get all ids
@vrledu I the moment I don't know. It would be easier to redsign your json to have consistent format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.