如果我有一个包含两个数组的对象,其中包含唯一值
{"all":["A","B","C","ABC"],"some":["B","C"]}
我怎样才能找到.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' )
虽然- 数组减法是最好的方法,但这是使用del和indices的另一种解决方案:
. as $d | .all | del(.[ indices($d.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"]