8

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

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

我怎样才能找到.all - .some

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

4

3 回答 3

14

@Jeff Mercado 让我大吃一惊!我不知道数组减法是允许的......

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

产量

[
  "A",
  "ABC"
]
于 2015-04-02T16:16:52.400 回答
4

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

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' )
于 2017-08-30T14:48:12.053 回答
1

虽然- 数组减法是最好的方法,但这是使用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"]
于 2017-08-30T16:19:39.610 回答