我有一個 json 檔案,大致如下所示:
{
"default": [
{
"name" : "Joe Bloggs",
"email" : "[email protected]"
}
],
"groups": [
{
"recipients" : [
{
"name" : "Jane Bloggs",
"email" : "[email protected]"
}
],
"orgs" : [
"Service A",
"Service B",
"Service C"
]
},
{
"recipients" : [
{
"name" : "Bill Gates",
"email" : "[email protected]"
}
],
"orgs" : [
"Service D",
"Service E"
]
},
{
"recipients" : [
{
"name" : "Steve Jobs",
"email" : "[email protected]"
}
],
"orgs" : [
"Service F",
"Service G"
]
}
]
}
使用 jq 我希望能夠使用其中一個組織進行搜索,例如“服務 A”并僅回傳收件人資訊
我可以使用 jq 輕松搜索收件人,例如:
cat /path/to/file.json | jq -r '.groups[] | .recipients[] | select(.name | contains("Jobs"))' )
回傳
{
"name": "Steve Jobs",
"email": "[email protected]"
}
但是,如果我嘗試通過 orgs 陣列進行搜索,則會收到錯誤訊息:
cat /path/to/file.json | jq -r '.groups[] | select(.orgs | contains("Service A"))' )
jq: error (at <stdin>:46): array (["Service A...) and string ("Service A") cannot have their containment checked
可以用 jq 做我正在尋找的東西嗎?
uj5u.com熱心網友回復:
取而代之的是,contains您需要index [ docs ]來檢查是否存在具有值的索引Service A:
.groups[] | select(.orgs | index("Service A"))
將輸出:
{
"recipients": [
{
"name": "Jane Bloggs",
"email": "[email protected]"
}
],
"orgs": [
"Service A",
"Service B",
"Service C"
]
}
JqPlay 演示
我們可以將其擴展為僅輸出recipients如下:
.groups[] | select(.orgs | index("Service A")) | .recipients | first
我們用來first從.recipients陣列中選擇第一個物件的地方。輸出將是:
{
"name": "Jane Bloggs",
"email": "[email protected]"
}
JqPlay 演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372613.html
