Search code examples
jsonkeyiterationjq

jq - How to iterate through keys of different names


I've got JSON that looks like this

{
  "keyword1": {
    "identifier1": 16
  },
  "keyword2": {
    "identifier2": 16
  }
}

and I need to loop through the keywords to get the identifiers (not sure if I'm using the right terminology here). Seems pretty simple, but because the keywords are all named different, I don't know how to handle that.


Solution

  • The original tag for this question was jq so here is a jq solution:

    .[] | keys[]
    

    For example, with the input as shown in the question:

    $ jq '.[] | keys[]' input.json
    
    "identifier1"
    "identifier2"
    

    To retrieve the key names in the order they appear in the JSON object, use keys_unsorted.