tips
20 tips Jq
One command, setting or habit at a time about Jq: what it does, the line to copy and a caveat or two.
Text processing 12
-
Turns JSON strings into single-quoted shell words that survive spaces and apostrophes.
jq -r '.files[] | @sh' data.json -
Takes only the first few results of a jq generator and quits early.
jq -n -c 'limit(3; range(1; 1000000000))' -
Passes any number of values from the shell to a jq filter as an array.
jq -n -c '$ARGS.positional' --args a "b c" -
Runs a filter on every key and value of a JSON object to rename or drop keys.
jq 'with_entries(.key |= ascii_upcase)' -
Edit a field in place, using its current value, without rebuilding the document.
jq '.replicas |= . + 1' deploy.json -
Turn ordinary text lines into strings jq can split, filter and wrap.
cut -d: -f1,7 /etc/passwd | jq -R 'split(":") | {user: .[0], shell: .[1]}' -
Sort records on a field and keep only the first few.
jq -c 'sort_by(-.mem) | .[:2] | map(.name)' containers.json -
Flatten records into tab separated lines that classic text tools can handle.
jq -r '.[] | [.name, .mem] | @tsv' containers.json | sort -t$'\t' -k2 -n | column -t -
Decode the middle part of a JWT to see its claims and expiry time.
echo "$TOKEN" | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson' -
Replace missing or null fields with a fallback value in jq output.
jq -r '.[] | "\(.name): \(.description // "no description")"' repos.json -
Count how many records share a value, straight from an API response.
jq -c 'group_by(.state) | map({state: .[0].state, count: length})' containers.json -
Prints JSON strings as plain text, so jq output works in scripts and loops.
echo '{"name":"nextdash"}' | jq -r '.name'
Scripting 6
-
Use a jq check directly in an if statement or a health check script.
if curl -fsS https://example.com/health | jq -e '.status == "ok"' >/dev/null; then -
Compare two JSON files without noise from key order or formatting.
diff <(jq -S . old.json) <(jq -S . new.json) -
Convert a flat object of settings into lines a shell or Docker can read.
echo '{"DB_HOST":"db","DB_PORT":5432,"DEBUG":false}' \ -
Pull values from environment variables into jq output without passing them as arguments.
export SITE=example.com RETRIES=3 -
Deep merge two config files so the second one overrides only what it sets.
cat defaults.json -
Hands shell variables to jq safely, as strings or as real JSON values.
NAME="web 1"
Network and DNS 2
-
See which subnet a Docker network uses and which address each container got.
docker network inspect $(docker network ls -q) \ -
Prints network information as JSON so a script can read an address reliably.
ip -j addr show eth0 | jq -r '.[0].addr_info[] | select(.family=="inet") | .local'
Nothing in this filter yet.