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 to_entries turns an object into KEY=value lines for a .env file

Jq
~/tips/tip-jq-to-entries-env-file

echo '{"DB_HOST":"db","DB_PORT":5432,"DEBUG":false}' \

Convert a flat object of settings into lines a shell or Docker can read.

Settings often arrive as an object in JSON, while Docker Compose and shell scripts want KEY=value lines. to_entries bridges the two.

echo '{"DB_HOST":"db","DB_PORT":5432,"DEBUG":false}' \
  | jq -r 'to_entries[] | "\(.key)=\(.value)"' > app.env
cat app.env
# DB_HOST=db
# DB_PORT=5432
# DEBUG=false

to_entries turns an object into an array of {key, value} pairs, so you can loop over the keys, which plain jq paths can’t do. The \( ) inside the string is jq’s string interpolation and fills in each key and value. from_entries does the reverse, and with_entries(...) lets you change keys or values and get an object back, like with_entries(.key |= ascii_upcase).

For a file you source in bash, values with spaces or quotes need quoting. Use \(.value | @sh) there, which wraps each value in safe single quotes.

Only flat objects make sense here. A nested object or array as a value gets printed as compact JSON text after the equals sign, which is rarely what the reading side expects. And be careful where the file ends up: an env file full of passwords shouldn’t be committed or left world readable, so I’d set chmod 600 on it.

Further reading: jq manual: to_entries, from_entries, with_entries

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