JQ:两个阵列的setdiff
如果一个对象有两个数组,其中包含唯一的值JQ:两个阵列的setdiff,jq,set-difference,Jq,Set Difference,如果一个对象有两个数组,其中包含唯一的值 {"all":["A","B","C","ABC"],"some":["B","C"]} 我怎样才能找到.all-.some 在这种情况下,我正在寻找[“A”,“ABC”]@Jeff Mercado让我大吃一惊!我不知道数组减法是允许的 echo -n '{"all":["A","B","C","ABC"],"some":["B","C"]}' | jq '.all-.some' 屈服 [ "A", "ABC" ] 我正在寻找一个类似的解决
{"all":["A","B","C","ABC"],"some":["B","C"]}
我怎样才能找到.all-.some
在这种情况下,我正在寻找
[“A”,“ABC”]
@Jeff Mercado让我大吃一惊!我不知道数组减法是允许的
echo -n '{"all":["A","B","C","ABC"],"some":["B","C"]}' | jq '.all-.some'
屈服
[
"A",
"ABC"
]
我正在寻找一个类似的解决方案,但要求动态生成阵列。下面的解决方案正好达到预期效果
array1=$(jq -e '') // jq expression goes here
array2=$(jq -e '') // jq expression goes here
array_diff=$(jq -n --argjson array1 "$array1" --argjson array2 "$array2"
'{"all": $array1,"some":$array2} | .all-.some' )
虽然这是最好的方法,但下面是另一个使用和的解决方案:
当您想知道删除了哪些元素时,它可能会有所帮助。例如,对于示例数据和-c
(压缩输出)选项,以下过滤器
. as $d
| .all
| [indices($d.some[])[]] as $found
| del(.[ $found[] ])
| "all", $d.all, "some", $d.some, "removing indices", $found, "result", .
产生
"all"
["A","B","C","ABC"]
"some"
["B","C"]
"removing indices"
[1,2]
"result"
["A","ABC"]
你不是已经有你想要的了吗
.all-.有些
您可以在最后执行$array1-$array2
"all"
["A","B","C","ABC"]
"some"
["B","C"]
"removing indices"
[1,2]
"result"
["A","ABC"]