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 |= changes one value and keeps the rest of the document

Jq
~/tips/tip-jq-update-assignment

jq '.replicas |= . + 1' deploy.json

Edit a field in place, using its current value, without rebuilding the document.

To change a single value in a config file or API payload, I’d use jq’s update operator |=. The rest of the document stays exactly as it was.

jq '.replicas |= . + 1' deploy.json
jq '.services[].image |= sub(":latest$"; ":1.4.2")' stack.json
jq 'map(.name |= ascii_downcase)' users.json

On the right side of |=, the dot is the current value of whatever is on the left. So .replicas |= . + 1 means “take replicas and replace it with itself plus one”. The left side can be a path that matches many places at once, like every image of every service in the second line, and each one gets updated.

That’s the difference with plain =. .replicas = 3 sets a fixed value, and on its right side the dot is the whole input document, not the field. Mixing the two up gives confusing results, so I’d use = for fixed values and |= when the new value depends on the old one.

jq never edits the file itself. It prints the changed document, and jq ... file.json > file.json leaves you with an empty file, because the shell truncates it before jq reads it. Write to a temporary file and move it back, or use sponge from moreutils. jq also reformats the whole file, so key order is kept but your indentation and spacing aren’t.

Further reading: jq manual: update assignment

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)' cut -d: -f1,7 /etc/passwd | jq -R 'split(":") | {user: .[0], shell: .[1]}' All Jq tips (20) All topics

Link