Daniel Daniel - 5 months ago 27
JSON Question

Select objects based on value of variable in object using jq

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"
).

Answer

After lots of googling finding mainly jQuery stuff, I found a blog post with the answer:

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}

From here: http://zerokspot.com/weblog/2013/07/18/processing-json-with-jq/