brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: jq group_by counts records per value, like GROUP BY in SQL

Jq
~/tips/tip-jq-group-by-count

jq -c 'group_by(.state) | map({state: .[0].state, count: length})' containers.json

Count how many records share a value, straight from an API response.

Questions like “how many containers are running and how many have exited” don’t need a database. jq can group and count.

jq -c 'group_by(.state) | map({state: .[0].state, count: length})' containers.json
# [{"state":"exited","count":1},{"state":"running","count":2}]

group_by(.state) takes an array and returns an array of arrays, one per distinct value, with all the matching records inside. Then map turns each group into a small summary: the value, read from the first record, and length, the number of records in that group.

You can put more in that summary. total: (map(.mem) | add) adds up a field per group, and names: map(.name) lists who’s in it.

For a quick table in the terminal I’d finish with .[] | [.state, .count] | @tsv and -r.

It only works on an array. If your input is a stream of separate objects, one per line, wrap them first with jq -s or [inputs]. And the groups come back sorted by the grouping value, not in the order they first appeared, so if order matters, sort the summary afterwards with sort_by(-.count) to get the biggest group first.

Further reading: jq manual: group_by

More Jq tips jq -r '.files[] | @sh' data.json jq -n -c 'limit(3; range(1; 1000000000))' jq -n -c '$ARGS.positional' --args a "b c" jq 'with_entries(.key |= ascii_upcase)' jq '.replicas |= . + 1' deploy.json All Jq tips (20) All topics

Link