Created
August 29, 2023 14:06
-
-
Save wader/4163da796082c3ddaf32e4602547c604 to your computer and use it in GitHub Desktop.
json diff with jq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# jq -n -L . 'include "diff"; diff({hello:1}; {hello:2, world: 3})' | |
# { | |
# "hello": { | |
# "a": 1, | |
# "b": 2 | |
# }, | |
# "world": { | |
# "b": 3 | |
# } | |
# } | |
# | |
# produce a/b pairs for diffing values | |
def diff($a; $b): | |
( ( $a | type) as $at | |
| ( $b | type) as $bt | |
| if $at != $bt then {a: $a, b: $b} | |
elif ($at == "array" or $at == "object") then | |
( [ ((($a | keys) + ($b | keys)) | unique)[] as $k | |
| { | |
($k | tostring): | |
( [($a | has($k)), ($b | has($k))] | |
| if . == [true, true] then diff($a[$k]; $b[$k]) | |
elif . == [true, false] then {a: $a[$k]} | |
elif . == [false, true] then {b: $b[$k]} | |
else empty # TODO: can't happen? error? | |
end | |
) | |
} | |
] | |
| add | |
| if . == null then empty end | |
) | |
else | |
if $a == $b then empty else {a: $a, b: $b} end | |
end | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment