Skip to content

Instantly share code, notes, and snippets.

@rgs
Created March 15, 2024 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgs/54fae0419a23229d8c69e6c01e999f0c to your computer and use it in GitHub Desktop.
Save rgs/54fae0419a23229d8c69e6c01e999f0c to your computer and use it in GitHub Desktop.
Get the intersection of an arbitrary number of json files with jq
#!/usr/bin/env bash
function intersectJson {
echo $* | \
jq -nS '
def intersect:
.[0] as $a |
.[1] as $b |
if ($a | type) == "object" then
if ($b | type) == "object" then
$a | reduce keys[] as $k ( {} ;
if $k | in($b) then
. + { $k: ( [ $a[$k], $b[$k] ] | intersect ) }
end
) | with_entries(select(.value != null and .value != {}))
else
null
end
elif ($a | type) == "array" then
if ($b | type) == "array" then
[ $a, $b ] | transpose | map(intersect)
else
null
end
elif $a == $b then
$a
else
null
end;
input as $first |
[ inputs ] |
reduce .[] as $i ( $first ; [ ., $i ] | intersect )
'
}
intersectJson $(cat $*)
# vim:ts=8:sts=2:sw=2:et
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment