如何过滤嵌套数组中不包含键值对的条目



假设我有以下 JSON 输出:

{
 "Stacks": [
        {
            "StackName": "hello-world",
            "Tags": [
                {
                    "Key": "environment",
                    "Value": "sandbox"
                },
                {
                    "Key": "Joe Shmo",
                    "Value": "Dev"
                }
            ]
        },
        {
            "StackName": "hello-man",
            "Tags": [
                {
                    "Key": "environment",
                    "Value": "live"
                },
                {
                    "Key": "Tandy",
                    "Value": "Dev"
                }
            ]
        }
    ]
}

我将如何编写一个jq查询来获取没有Tags"Key": "Joe Shmo"堆栈的所有StackName所以结果会简单地返回hello-man.

.Stacks[]
| select( any(.Tags[]; .Key == "Joe Shmo" ) | not)
| .StackName

这有效地检查相等性(any具有短路语义),而contains会检查包含。

使用 contains ,像这样:

jq -r '.Stacks[]|select(.Tags|contains([{"Key": "Joe Shmo"}])|not).StackName'

注意:-r从输出中删除引号,否则jq会打印"hello-man"(在双引号内)

最新更新