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 sorts keys, so diff shows what really changed between two files

Jq
~/tips/tip-jq-sort-keys-diff

diff <(jq -S . old.json) <(jq -S . new.json)

Compare two JSON files without noise from key order or formatting.

Diffing two JSON files directly is useless when one is minified or the keys are in a different order. I’d normalise both with jq first.

diff <(jq -S . old.json) <(jq -S . new.json)
# 4c4
# <     "y": 2
# ---
# >     "y": 3

-S sorts the keys of every object, at every level, and the . filter pretty prints the whole document with the same indentation. Two files with the same data now produce identical text, so diff only shows lines whose values actually changed. The <(...) is process substitution in bash and zsh, which hands the output to diff as if it were a file.

It is handy for comparing an API response before and after a change, or a config exported from two servers. Add -u to diff for the more familiar unified format, or swap in git diff --no-index for colours.

Arrays keep their order, and that’s correct, since order means something in an array. It does mean that the same list in a different order shows up as a big change. If the order doesn’t matter for your data, sort those arrays too, like jq -S '.hosts |= sort' file.json. And diff exits with 1 when the files differ, so remember that if you use this in a script with set -e.

Further reading: jq manual: –sort-keys

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