6

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 Answer 1

7
+50

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]
4
  • 1
    input | jq -r 'to_entries | map(select(.value.primary == true) | .key)[0]' to just get foo
    – nbari
    Commented May 26, 2020 at 21:31
  • 1
    The == true isn't necessary; as foo == true has the same truth value as foo itself for any boolean-valued foo.
    – chepner
    Commented May 26, 2020 at 21:38
  • Thanks both. I incorporated your suggestions. Commented May 26, 2020 at 21:42
  • Ah, to_entries is just what I needed. That worked perfectly. Many thanks!
    – Crell
    Commented May 27, 2020 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.