I have the following json file:
{     "FOO": {         "name": "Donald",         "location": "Stockholm"     },     "BAR": {         "name": "Walt",         "location": "Stockholm"     },     "BAZ": {         "name": "Jack",         "location": "Whereever"     } }  I am using jq and want to get the "name" elements of the objects where 'location' is 'Stockholm'.
I know I can get all names by
cat json | jq .[] | jq ."name" "Jack" "Walt" "Donald"  But I can't figure out how to print only certain objects, given the value of a sub key (here: "location" : "Stockholm").
Adapted from this post on Processing JSON with jq, you can use the select(bool) like this:
$ jq '.[] | select(.location=="Stockholm")' json {   "location": "Stockholm",   "name": "Walt" } {   "location": "Stockholm",   "name": "Donald" } 
                        To obtain a stream of just the names:
$ jq '.[] | select(.location=="Stockholm") | .name' json   produces:
"Donald" "Walt"   To obtain a stream of corresponding (key name, "name" attribute) pairs, consider:
$ jq -c 'to_entries[]         | select (.value.location == "Stockholm")         | [.key, .value.name]' json   Output:
["FOO","Donald"] ["BAR","Walt"] 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With