364

次のjsonファイルがあります。

{
    "FOO": {
        "name": "Donald",
        "location": "Stockholm"
    },
    "BAR": {
        "name": "Walt",
        "location": "Stockholm"
    },
    "BAZ": {
        "name": "Jack",
        "location": "Whereever"
    }
}

私は jq を使用しており、「場所」が「ストックホルム」であるオブジェクトの「名前」要素を取得したいと考えています。

私はすべての名前を取得できることを知っています

cat json | jq .[] | jq ."name"
"Jack"
"Walt"
"Donald"

しかし、サブキーの値を指定して、特定のオブジェクトのみを出力する方法がわかりません (ここでは: "location" : "Stockholm")。

4

4 に答える 4

534

jq を使用した JSON の処理に関するこの投稿から適応すると、次のselect(bool)ように使用できます。

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}
于 2013-09-04T07:42:01.470 に答える
250

名前だけのストリームを取得するには:

$ jq '.[] | select(.location=="Stockholm") | .name' json

生成:

"Donald"
"Walt"

対応する (キー名、「名前」属性) ペアのストリームを取得するには、次のことを考慮してください。

$ jq -c 'to_entries[]
        | select (.value.location == "Stockholm")
        | [.key, .value.name]' json

出力:

["FOO","Donald"]
["BAR","Walt"]
于 2015-08-10T04:50:15.597 に答える
20

これをシェルに完全にコピーして貼り付けるだけで、それを把握できます。

# pass the multiline string to the jq, use the jq to 
# select the attribute named "card_id" 
# ONLY if its neighbour attribute
# named "card_id_type" has the "card_id_type-01" value.
# jq -r means give me ONLY the value of the jq query no quotes aka raw


cat << EOF | \
    jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'
    [  
     { "card_id": "id-00", "card_id_type": "card_id_type-00"},
     { "card_id": "id-01", "card_id_type": "card_id_type-01"},
     { "card_id": "id-02", "card_id_type": "card_id_type-02"}
    ]
EOF
# this ^^^ MUST start first on the line - no whitespace there !!!
# outputs:
# id-01

または aws cli コマンドを使用

 # list my vpcs or
 # list the values of the tags which names are "Name" 
 aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]
        |select (.Key == "Name") | .Value'|sort  -nr

フィルタリング段階と選択段階の両方で、階層内を上下に移動できることに注意してください。

 kubectl get services --all-namespaces -o json | jq -r '
 .items[] | select( .metadata.name 
     | contains("my-srch-string")) | 
     { name: .metadata.name, ns: .metadata.namespace 
     , nodePort: .spec.ports[].nodePort
     , port: .spec.ports[].port}
 '
于 2020-10-05T16:00:28.600 に答える