jq group_by : Group Array Elements by a Key
jq group_by(f) sorts the array by f then splits it into sub-arrays where f is equal.
group_by buckets API items, for example grouping workflow runs by status before counting each bucket in a report step.
What it does
group_by(f) first sorts the input array by f, then partitions adjacent equal-keyed elements into sub-arrays. The result is an array of arrays. It is the building block for counting or summing per group.
Common usage
# group runs by status
jq 'group_by(.status)' runs.json
# count per group
jq 'group_by(.status) | map({status: .[0].status, count: length})' runs.json
# group then sum a field per bucket
jq 'group_by(.author) | map({author: .[0].author, total: (map(.size)|add)})' commits.jsonFunctions
| Function | What it does |
|---|---|
| group_by(f) | Array of sub-arrays grouped by f |
| sort_by(f) | Sort the array by f |
| unique_by(f) | Drop duplicates by f |
| .[0].field | Read the group key from the first element |
Common errors in CI
"jq: error: Cannot iterate over null (null)" means group_by received null instead of an array. "jq: error: null (null) and string cannot be compared" means f is missing on some elements; the implicit sort cannot compare null with a string. Filter those out with select(.field != null) first.