JQ:两个数组的setdiff

时间:2015-04-01 16:34:39

标签: jq set-difference

如果我有一个包含两个包含唯一值的数组的对象

{"all":["A","B","C","ABC"],"some":["B","C"]}

如何找到.all - .some

在这种情况下,我正在寻找["A","ABC"]

3 个答案:

答案 0 :(得分:4)

@Jeff Mercado引起了我的注意!我不知道允许数组减法......

echo -n '{"all":["A","B","C","ABC"],"some":["B","C"]}' | jq '.all-.some'

产量

[
  "A",
  "ABC"
]

答案 1 :(得分:0)

我一直在寻找类似的解决方案,但要求数组是动态生成的。以下解决方案只是做了预期的

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' )

答案 2 :(得分:0)

尽管- Array Subtraction是最佳方法,但使用delindices是另一种解决方案:

. 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"]