How do I extract a key with jq based on its child values

Viewed 787

I'm trying to process some JSON with jq. Specifically, I want a particular key, based on its child value. Example, given:

{
  "foo": {"primary": true, "blah": "beep"},
  "bar": {"primary": false, "blah": "narf"},
  "baz": {"primary": false, "blah": "poink"},
}

I want the string "foo", because that is the key whose child value "primary' is true. (I can guarantee that one and only one entry will have primary = true, due to what's generating the JSON.)

So far the best I've been able to manage is:

jq -r '.[] | select(.primary == true)'

But that returns the value of "foo", not the string "foo" itself. Digging through the manual so far I've not found a way to grab the key specifically.

Any pointers you can provide?

1 Answers

You need to "split" your object into an array of entries, e.g.

[
  {
    "key": "foo",
    "value": {
      "primary": true,
      "blah": "beep"
    }
  }
  //...
]

Then you can filter with .value.primary and map the result with .key:

to_entries | map(select(.value.primary)  | .key)

Returns:

[
  "foo"
]

Or to get just the first item of the array: (Thanks @nbari)

to_entries | map(select(.value.primary)  | .key)[0]
Related