簡體   English   中英

使用 JQ 在具有相同鍵的對象列表中搜索特定鍵、值對

[英]Searching a list of objects with identical keys for specific key, value pairs with JQ

對於如下所示的 JSON object,

{
    "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”的“name”字段和包含“CEO”的“title”字段,它就會將公司作為有效結果返回。 這意味着如果應用於上面的 JSON object,此過濾器將返回兩個公司,如在 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"
      }
    ]
  }
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM