Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
Adam vonNieda Avatar asked Jan 29 '16 14:01

Adam vonNieda


3 Answers

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.

like image 151
peak Avatar answered Oct 17 '22 23:10

peak


I'd think something along these lines would work well:

jq '. | to_entries | .[].key'

see https://stedolan.github.io/jq/manual/#to_entries,from_entries,with_entries

or if you wanted to get the values from a variable:

JSON_DATA={main:{k1:v1,k2:v2}}
result=$(jq -n "$JSON_DATA" | jq '.main | to_entries | .[].value' --raw-output)
echo $result

##outputs: v1 v2
like image 21
bristweb Avatar answered Oct 17 '22 23:10

bristweb


I came here hoping to sort out a bunch of keys from my JSON, I found two features handy. There are three functions "to_entries", "from_entries", and "with_entries". You can filter the values by key or value, like so:

JSON_DATA='
{
  "fields": {
    "first": null,
    "second": "two",
    "third": "three"
  }
}
'

echo "$JSON_DATA" | jq '{fields: .fields | with_entries(select(.value != null and .key != "third")) }'

Output:

{
  "fields": {
    "second": "two"
  }
}
like image 5
turiyag Avatar answered Oct 18 '22 00:10

turiyag