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 -c prints each JSON result on a single line

Json
~/tips/tip-jq-compact-output-c

jq -c '.[]' hosts.json

Prints every jq result as one compact line, ready for loops and line-based tools.

By default jq pretty-prints, which is lovely to read and annoying to process. One object spread over twelve lines doesn’t fit in grep or a while read loop. -c (--compact-output) puts each result on its own single line instead.

jq -c '.[]' hosts.json

If hosts.json is an array of objects, .[] takes them out one by one and -c prints each as one line. That’s the JSON Lines format a lot of tools like, and it plays nicely with the classic shell tools.

An example where that matters: looping over the objects in a shell script. Each line is a complete JSON object, so you can hand it to jq again inside the loop:

jq -c '.[]' hosts.json | while read -r host; do
  name=$(echo "$host" | jq -r '.name')
  ip=$(echo "$host" | jq -r '.ip')
  echo "$name is on $ip"
done

Without -c, read would get a lone { on the first pass and fall apart. Compact output is also nice for grep: you get whole objects back, never half of one.

Keep the flags apart, though. -c still prints valid JSON, so strings keep their quotes; for bare text you want -r. A string that contains a newline also stays on one line, because JSON writes it as \n. That’s what line-based tools need, but the line can get long. If you want the opposite for reading, --indent 4 or --tab changes the pretty-printing instead.

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