我有以下json文件:
{
"FOO": {
"name": "Donald",
"location": "Stockholm"
},
"BAR": {
"name": "Walt",
"location": "Stockholm"
},
"BAZ": {
"name": "Jack",
"location": "Whereever"
}
}我正在使用jq,并且想要获取对象的"name“元素,其中”location“是”斯德哥尔摩“。
我知道我可以得到所有的名字
cat json | jq .[] | jq ."name"
"Jack"
"Walt"
"Donald"但是,给定子键(这里:"location" : "Stockholm")的值,我不知道如何只打印某些对象。
发布于 2013-09-04 15:42:01
改编自Processing JSON with jq上的这篇文章,你可以这样使用select(bool):
$ jq '.[] | select(.location=="Stockholm")' json
{
"location": "Stockholm",
"name": "Walt"
}
{
"location": "Stockholm",
"name": "Donald"
}发布于 2015-08-10 12:50:16
要获取仅包含名称的流,请执行以下操作:
$ jq '.[] | select(.location=="Stockholm") | .name' json产生:
"Donald"
"Walt"要获得对应的(key name,"name“属性)对的流,请考虑:
$ jq -c 'to_entries[]
| select (.value.location == "Stockholm")
| [.key, .value.name]' json输出:
["FOO","Donald"]
["BAR","Walt"]发布于 2020-10-06 00:00:29
只需尝试这个作为一个完整的拷贝粘贴在外壳中,你就会掌握它。
# create the example file to be working on ..
cat << EOF > tmp.json
[
{ "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
# pass the content of the file to the jq query, which gets the array of objects
# and 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
jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id' <tmp.json
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("api-doc")) | \
{ name: .metadata.name, ns: .metadata.namespace , nodePort: .spec.ports[].nodePort, port: .spec.ports[].port}'https://stackoverflow.com/questions/18592173
复制相似问题