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 // operator fills in a default when a field is missing

Jq
~/tips/tip-jq-alternative-default

jq -r '.[] | "\(.name): \(.description // "no description")"' repos.json

Replace missing or null fields with a fallback value in jq output.

API responses are rarely complete. jq’s alternative operator // gives me a fallback when a field is missing, so the output doesn’t fill up with null.

jq -r '.[] | "\(.name): \(.description // "no description")"' repos.json
jq '.port // 8080' settings.json

a // b returns a unless it’s null or false, and b otherwise. A field that’s missing reads as null, so both “not there” and “explicitly null” get the default.

It also combines well with empty. .email // empty skips records without an email entirely instead of printing a null line, which is handy before piping the result into another command.

The false part is where it bites. A config with "debug": false and a filter .debug // true gives you true, the exact opposite of what the file says. For boolean fields I’d use if has("debug") then .debug else true end instead. Zero and empty strings are fine, by the way: 0 // 5 stays 0, because only null and false count as missing. That’s different from JavaScript’s || and catches people coming from there.

Further reading: jq manual: alternative operator

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