Any JQ built-in function returning index of element in JSON array? Any JQ built-in function returning index of element in JSON array? arrays arrays

Any JQ built-in function returning index of element in JSON array?


to_entries should work perfectly.

jq -n '["a","b","c"] | to_entries'

will produce

[{"key":0,"value":"a"},{"key":1,"value":"b"},{"key":2,"value":"c"}]


There are two robust (i.e., that work in jq 1.3, 1.4 and 1.5) ways to iterate through an array with an index: one is to use keys[] (which works on arrays as well as objects), and the other using range/2. These two approaches can be illustrated as follows, assuming $a is an array:

($a | keys[]) as $i | [$i, $a[$i]] range(0; $a | length) as $i | [$i, $a[$i]]

Or more succinctly:

$a | keys[] as $i | [$i, .[$i]]$a | range(0;length) as $i | [$i, .[$i]]

If your jq has keys_unsorted, you might wish to use it instead.

(index/1 is probably not what is needed here.)


As of jq 1.4, there's index/1 or indices/1 as outlined in the manual.