5

Say I have data something like this:

{
  "18" : [ 2, 3, 3 ],
  "28" : [ 2, 2, 7 ],
  "45" : [ 3, 3, 5 ]
}

I'd like to make a jq query that returns the key/keys of the object with the array that contains a given value. For example, 2 exists in keys "18" and "28", and 7 exists only exists in "28". It is the name of the parent object I'm interested in finding. I've been through the manual and I can't seem to find an example of anything like this.

1 Answer 1

7

Using map_values to select only the arrays that contain the given value $val, then pulling out the keys of those arrays:

jq -r --argjson val 2 'map_values(select(contains([$val]))) | keys[]' file

contains() returns true if the given array ([$val]) is fully contained in the input to the function. If contains() returns true for an array in the input, select() will return that array.

I'm using map_values() to perform this selection of the arrays associated with the keys in the input object. This will give me a slimmed-down object with the arrays that pass the selection, and passing the result to keys will then give me an array of keys, which I unpack into a set of loose strings with the final [].

For the given input data, with 2 as the value of $val, this returns

18
28

I'm using --argjson rather than --arg to pass the value 2 into the expression as $val as the data is numeric, not strings.

2
  • The answer is perfect, but I'm am still unclear what map_values is doing. The query cannot be run without it: jq -r --argjson val 2 'select(contains([$val]))' test.json results in jq: error (at test.json:4): object ({"18":[2,3,...) and array ([2]) cannot have their containment checked. And the manual for map_values isn't what I expect at all.
    – A. Que
    Commented Jun 21, 2022 at 12:32
  • @A.Que map_values() works like map(), but takes an object as input rather than an array. The expression that map_values() evaluates is evaluated on the values in the object. In the answer above, I'm doing a select(), which effectively removes the values that we don't want to keep.
    – Kusalananda
    Commented Jun 21, 2022 at 12:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .