2015-04-01 48 views
1

如果我有setdiff包含在它独特的价值JQ:两个数组

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

我如何才能找到.all - .some两个数组对象?

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

+3

不要你已经知道你在找什么? '.all - .some' – 2015-04-01 17:40:06

回答

3

@Jeff梅尔卡多吹我的心!我不知道阵列减法被允许...

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

产生

[ 
    "A", 
    "ABC" 
] 
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') 
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"]