Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select objects based on value of variable in object using jq

Tags:

json

bash

select

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

like image 428
Daniel Avatar asked Sep 03 '13 12:09

Daniel


2 Answers

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" } 
like image 73
Daniel Avatar answered Sep 18 '22 12:09

Daniel


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"] 
like image 23
peak Avatar answered Sep 19 '22 12:09

peak