2015-04-15 41 views
2

我有一個json對象數組,我想提取數組的一個子集,使.name字段匹配一組輸入字符串。JQ:選擇具有鍵值在一組值中的對象

例如,我想完成以下操作。

jq -n '["a","b","c","d","e"] | map({name:.,foo:"bar"})' \ 
    | jq 'map(select(.name=="a" or .name=="c"))' 

我已經想出了以下解決方案,但我的[...]add用法好像我失去了一些東西聰明。

jq -n '["a","b","c","d","e"] | map({name:.,foo:"bar"})' \ 
    | jq --arg name 'a c' ' 
     [ 
     ($name | split(" "))[] as $name 
     | map(select(.name == $name)) 
     | add 
     ]' 

此外,這種解決方案迫使我多次迭代輸入數組而不是單遍。任何其他想法我怎麼能解決這個問題?

回答

3

將所有內容移動到select的條件中。你不需要對jq進行兩次獨立的調用。

$ echo '["a","b","c","d","e"]' | jq --arg names 'a c' 
    'map(select(. == ($names | split(" ")[])) | { name: ., foo: "bar" })' 
[ 
    { 
    "name": "a", 
    "foo": "bar" 
    }, 
    { 
    "name": "c", 
    "foo": "bar" 
    } 
] 
+0

我正在使用第一個jq生成對象格式數組的樣本輸入,我正在解析...您的答案完全正確,只是索引稍有不同。 'map(select(.name ==($ names | split(「」)[])))' – Jon

+0

請問,請你細分語法元素嗎?我無法理解這個perl-esqe系列特殊字符試圖完成什麼<3 – ThorSummoner

1

ThorSummoner的點,這裏 是使用--argjson內部與在不同的行 註釋的更少的perl-esqe溶液,它利用殼'行爲優點:

$ echo '["a","b","c","d","e"]' | jq --argjson wanted '["a","c"]' ' 
    .[]       # break array into elements 
| if ([.]|inside($wanted))  # if element is in wanted 
    then {name: ., foo:"bar"} # generate desired output 
    else empty     # otherwise generate nothing 
    end 
' 
相關問題