[英]Select objects based on value of variable in object using jq
我有以下 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"
)。
改編自使用 jq 處理 JSON 的這篇文章,您可以像這樣使用select(bool)
:
$ jq '.[] | select(.location=="Stockholm")' json
{
"location": "Stockholm",
"name": "Walt"
}
{
"location": "Stockholm",
"name": "Donald"
}
要獲取僅包含名稱的流:
$ jq '.[] | select(.location=="Stockholm") | .name' json
產生:
"Donald"
"Walt"
要獲得相應(鍵名、“名稱”屬性)對的流,請考慮:
$ jq -c 'to_entries[]
| select (.value.location == "Stockholm")
| [.key, .value.name]' json
輸出:
["FOO","Donald"]
["BAR","Walt"]
我有一個類似的相關問題:如果您想要恢復原始對象格式(帶有鍵名,例如 FOO、BAR)怎么辦?
Jq 提供了to_entries
和from_entries
來在對象和鍵值對數組之間進行轉換。 連同map
周圍的選擇
這些函數在對象和鍵值對數組之間進行轉換。 如果向 to_entries 傳遞了一個對象,那么對於輸入中的每個 k: v 條目,輸出數組包含 {"key": k, "value": v}。
from_entries 進行相反的轉換,而 with_entries(foo) 是 to_entries | 的簡寫。 地圖(富) | from_entries,用於對對象的所有鍵和值進行一些操作。 from_entries 接受鍵、鍵、名稱、名稱、值和值作為鍵。
jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'
{
"FOO": {
"name": "Donald",
"location": "Stockholm"
},
"BAR": {
"name": "Walt",
"location": "Stockholm"
}
}
使用with_entries
簡寫,這變成:
jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
"FOO": {
"name": "Donald",
"location": "Stockholm"
},
"BAR": {
"name": "Walt",
"location": "Stockholm"
}
}
只需嘗試將此作為 shell 中的完整復制粘貼,您就會掌握它。
# 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.