對于像下面這樣的 JSON 物件,
{
"company1": {
"employees": [
{
"name": "John",
"title": "CEO"
},
{
"name": "Jason",
"title": "CFO"
},
{
"name": "Jackson",
"title": "Sales Representative"
}
]
},
"company2": {
"employees": [
{
"name": "Amy",
"title": "CEO"
},
{
"name": "James",
"title": "Software Engineer"
},
{
"name": "John",
"title": "Sales Representative"
}
]
}
}
假設我要查找 CEO 名為 John 的所有公司。我試過使用這個過濾器:
map_values(select(.employees | select((.[] .name | contains("John")) and (.[] .title | contains("CEO")) )))
它實質上在整個串列中搜索包含“John”的“name”欄位和包含“CEO”的“title”欄位。問題是,只要員工串列中的某個地方有一個包含“John”的“姓名”欄位和一個包含“CEO”的“職務”欄位,它就會將公司作為有效結果回傳。這意味著如果應用于上面的 JSON 物件,此過濾器將回傳兩家公司,如在 company2 中,確實有一個名為 John 的員工(但他不是 CEO),并且有一個 CEO(但她不是 John)。
如何讓它正常作業(不改變資料結構)并且只回傳 company1?
uj5u.com熱心網友回復:
用于and匹配這兩個條件,如果至少有一名員工滿足條件,則使用anywithin使公司通過:select
map_values(select(any(.employees[]; .name == "John" and .title == "CEO")))
{
"company1": {
"employees": [
{
"name": "John",
"title": "CEO"
},
{
"name": "Jason",
"title": "CFO"
},
{
"name": "Jackson",
"title": "Sales Representative"
}
]
}
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490925.html
