C-nan
C-nan

Reputation: 364

Find parent key based on child value

I have the following JSON. I want to know from which country "Jan" is (Belgium).

{
    "Belgium": [
        {
            "first_name": "Jan",
            "last_name": "Molenaar"
        },
        {
            "first_name": "Piet",
            "last_name": "Hoogenboom"
        }
    ],
    "Germany": [
        {
            "first_name": "Herman",
            "last_name": "Bret"
        },
        {
            "first_name": "Sanne",
            "last_name": "Klepper"
        }
    ]
}

I found and tried different queries, such as:

cat data.json |jq '. as $parent | select(.first_name == "Jan") | $parent'

But unfortunately, I am unable to find the correct query.

Upvotes: 1

Views: 653

Answers (2)

peak
peak

Reputation: 116650

The following prevents the production of repetitions when "Jan" is the first name of several individuals, and is also more efficient than alternatives that unconditionally scan through all "first_name" values:

to_entries[] | select( any(.value[]; .first_name=="Jan")).key

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50750

Get the path to the entry whose first_name is Jan as an array, and extract the country name from it.

path(.[][] | select(.first_name == "Jan"))[0]

Online demo

Upvotes: 1

Related Questions