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 -s reads all the JSON input into one array so you can count or sum it

Json
~/tips/tip-jq-slurp-count-sum

jq -s 'length' events.jsonl

Collects every JSON value from the input into one array, so you can count, sum or merge them.

jq normally handles its input one JSON value at a time. That’s great until you want an answer about all of them together, like how many entries a JSON log has or what a field adds up to. The -s flag (--slurp) reads the whole input into one big array first and runs your filter once on that.

jq -s 'length' events.jsonl

On a file with one JSON object per line, that prints the number of objects. Without -s, length would run on each object separately and print the number of keys in each, which is not what you asked.

Once everything is in one array, the usual array filters work. To add up a bytes field across every entry:

jq -s 'map(.bytes) | add' events.jsonl

It also works across files. jq -s '.' a.json b.json gives you one array holding the contents of both files, which is a quick way to merge a couple of exports into a single file.

My advice is to watch the size. Slurp loads everything into memory, which is fine for a few megabytes and a bad idea for a multi-gigabyte log. For that, the manual points at reduce with inputs and the -n flag, which goes through the values one by one and keeps only a running result:

jq -n 'reduce inputs as $e (0; . + $e.bytes)' events.jsonl

Leave out -n there and the first object goes missing from your total, which the manual warns about too.

Further reading: jq 1.8 manual

More Json tips echo '{"id":1,"payload":"{\"user\":\"ann\",\"tags\":[\"x\",\"y\"]}"}' | jq -c '.payload | fromjson | .tags' jq empty config.json Paths() tells you where in a big JSON document a value lives jq -c --slurpfile u users.json ' jq -cn --stream 'fromstream(1|truncate_stream(inputs))' big.json All Json tips (9) All topics

Link