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 sort_by with a slice gives you the top 5 of anything

Jq
~/tips/tip-jq-sort-by-top-n

jq -c 'sort_by(-.mem) | .[:2] | map(.name)' containers.json

Sort records on a field and keep only the first few.

Finding the five biggest of something in an API response is a two step filter in jq: sort, then slice.

jq -c 'sort_by(-.mem) | .[:2] | map(.name)' containers.json
# ["db","web"]

jq -r 'sort_by(.updated) | reverse | .[:5][] | .name' repos.json

sort_by(.mem) sorts the array from small to large on that field. For biggest first I’d either negate a number, like -.mem, or add reverse afterwards, which also works for strings and dates. Then .[:5] slices off the first five, the same slice syntax Python uses. Adding [] after the slice unpacks the result so each item goes on its own line.

You can sort on several fields at once with sort_by(.state, .name): first on state, and on name when states are equal.

The trap is missing values. Records without the field get null, and in jq null sorts before everything else. With reverse those end up last, which is fine, but with -.mem jq throws an error because you can’t negate null. If some records lack the field, give it a default first: sort_by(-(.mem // 0)). Also, ISO dates sort fine as strings, but dates like 30-11-2026 don’t.

Further reading: jq manual: sort, sort_by, jq manual: slices

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