Created
March 15, 2024 12:20
-
-
Save rgs/54fae0419a23229d8c69e6c01e999f0c to your computer and use it in GitHub Desktop.
Get the intersection of an arbitrary number of json files with jq
This file contains hidden or 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
#!/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