2015-04-01 51 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"]