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 '. * input' merges a config file with an override file

Jq
~/tips/tip-jq-merge-config-files

cat defaults.json

Deep merge two config files so the second one overrides only what it sets.

When you have a default config and a small file with local changes, jq can merge them into one, nested sections included.

cat defaults.json
# {"db": {"host": "localhost", "port": 5432}, "debug": false}
cat override.json
# {"db": {"port": 5433}, "debug": true}

jq '. * input' defaults.json override.json
# {"db": {"host": "localhost", "port": 5433}, "debug": true}

jq reads the first file as ., and input pulls in the next one. The * operator on two objects merges them recursively: keys from the right side win, and nested objects are merged key by key instead of replaced. That’s why db.host survives while db.port changes.

The plain + operator is the shallow version. With +, the whole db object from the override replaces the default one and you lose the host. For layered config that’s almost never what I want.

Arrays aren’t merged, they’re replaced. If the default has a list of five allowed hosts and the override has one, you end up with one. When you need to add to a list, do it explicitly with + on that path. And keep the file order in mind: whatever comes second wins, so swapping the two arguments silently turns your override into the default.

Further reading: jq manual: multiplication of objects, jq manual: input

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