在具有相同键的对象列表中搜索具有JQ的特定键值对



对于像下面这样的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"还有一个"标题"包含"ceo"的字段。问题是,只要在员工名单的某个地方有一个"名字"。字段中包含"John"还有一个"标题"字段包含"CEO",它将返回公司作为有效结果。这意味着如果将此过滤器应用于上面的JSON对象,则将返回两个公司,如在company2中,确实有一个名为John的员工(但他不是CEO),并且有一个CEO(但她不是John)。

如何让它正确工作(不改变数据的结构),只返回company1?

使用and来匹配两个条件,如果select中至少有一个员工满足条件,则使用any来通过该公司:

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"
}
]
}
}

演示

最新更新