Parent object key of array that contains value with jq

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.

Asked By: A. Que

||

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.

Answered By: Kusalananda
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.