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 @tsv turns API output into columns for cut, sort and awk

Jq
~/tips/tip-jq-tsv-columns

jq -r '.[] | [.name, .mem] | @tsv' containers.json | sort -t$'\t' -k2 -n | column -t

Flatten records into tab separated lines that classic text tools can handle.

Once data is out of JSON and into plain lines, all the old tools work again. jq’s @tsv format is the bridge I like best.

jq -r '.[] | [.name, .state, .mem] | @tsv' containers.json
# web     running 120
# db      exited  300
# cache   running 50

jq -r '.[] | [.name, .mem] | @tsv' containers.json | sort -t$'\t' -k2 -n | column -t

You build an array with the fields you want, in the order you want, and @tsv joins it with tabs. The -r matters: without it every line comes out as a quoted JSON string with \t in it. After that, sort, cut -f2, awk -F'\t' and column -t all do what you’d expect.

I’d pick tabs over @csv for terminal work because names rarely contain tabs, so splitting stays simple. @csv quotes every string, which is right for a spreadsheet and clumsy for cut.

Nested values don’t fit in a column. An array or object field makes @tsv stop with an error, so pick a scalar inside it or turn it into text first, for example (.tags | join(",")). Tabs and newlines inside values are escaped as \t and \n, which keeps one record per line but means you see the escapes literally.

Further reading: jq manual: format strings

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