jq - How to iterate through keys of different names

Adam vonNieda picture Adam vonNieda · Jan 29, 2016 · Viewed 17.8k times · Source

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.

Answer

peak picture peak · Jan 29, 2016

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.