How to filter the elements in a dictionary to iterate over

I feel silly for asking this since I can’t imagine this being overly complicated but I can’t for the love of god figure out how to do this. To clarify, consider this arbitrary json file:

{
  "animals" : [
         { "cat" : { "weight": 5, "color": "black", "adopted" : true}},
         { "cat" : { "weight": 5, "color": "white" }},
         { "dog" : { "weight": 10, "color": "grey" }},
         { "dog" : { "weight": 10, "color": "brown", "has_collar" : "yes" }},
         { "cat" : { "weight": 5, "color": "black", "adopted" : false}}
  ]
}

The thing I want to do is create a for loop that iterates over all of the cats defined in the collection of animals. I have found Range, where, in - but I can’t get any combination to work. What is the syntax to do what I request?

The data structure is a bit odd. Can you restructure it?

{
  "animals": [
    {
      "adopted": true,
      "color": "black",
      "species": "cat",
      "weight": 5
    },
    {
      "color": "white",
      "species": "cat",
      "weight": 5
    },
    {
      "color": "grey",
      "species": "dog",
      "weight": 10
    }
  ]
}

Unfortunately not, the file is external to me and I have to adhere to the standard it enforces.

What I’ve done for now is what feels to me a workaround:

{{ range .animals }}
{{ if .cat }}
This is a cat!
{{ end }}
{{ end }}

Which works, but I would have expected an option to do the iteration + filter in a single statement?

Not with your data structure.

That explains why I couldn’t find it then :slight_smile: Thanks for the elaboration as always! :1+:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.