Arrays

Array length, flatten & slice with jq

2 min read

Everyday array operations in jq.

length — count elements (or string/object size)

echo '[10,20,30]' | jq 'length'        # 3
echo '"hello"' | jq 'length'           # 5  (string length)
echo '{"a":1,"b":2}' | jq 'length'     # 2  (number of keys)

Count matches after a filter:

jq '[.[] | select(.active)] | length' data.json

flatten — collapse nested arrays

echo '[[1,2],[3,[4]]]' | jq 'flatten'      # [1,2,3,4]
echo '[[1,2],[3,[4]]]' | jq 'flatten(1)'   # [1,2,3,[4]]  (one level)

slice — a range of elements

echo '[0,1,2,3,4,5]' | jq '.[2:5]'     # [2,3,4]
echo '[0,1,2,3,4,5]' | jq '.[:3]'      # [0,1,2]  (first 3)
echo '[0,1,2,3,4,5]' | jq '.[-2:]'     # [4,5]    (last 2)

first / last

jq 'first(.[])' data.json     # first element
jq 'last(.[])' data.json      # last element
jq '.[0], .[-1]' data.json    # first and last

sum, min, max of numbers

echo '[10,20,30]' | jq 'add'                  # 60
echo '[10,20,30]' | jq 'min, max'             # 10 then 30
jq '[.[].price] | add' data.json              # sum a field across objects

reverse

echo '[1,2,3]' | jq 'reverse'     # [3,2,1]

add is the swiss-army aggregator: on numbers it sums, on strings it concatenates, on arrays it flattens-one-level, on objects it merges. [.[].field] | add is the idiom for “total this field across all records”.

Open the full version (with copy buttons) ↗

← All recipes