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

4 Answers
4

Leave a Comment