【问题标题】:How can I filter for entries that do NOT contain a key-value pair within a nested array如何过滤嵌套数组中不包含键值对的条目
【发布时间】:2019-01-11 00:46:26
【问题描述】:

假设我有以下 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" 的堆栈的StackNames?所以结果会简单地返回hello-man

【问题讨论】:

    标签: json select jq negation


    【解决方案1】:
    .Stacks[]
    | select( any(.Tags[]; .Key == "Joe Shmo" ) | not)
    | .StackName
    

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

    【讨论】:

    • 我正在检查 .Tags 是否包含具有 exact 键“Joe Shmo”的对象。至少我认为我的代码是这样做的
    • 天哪!我现在明白你的意思了。说真的,这很容易被误解。特别是因为手册没有提到它。如果我是作者,我会在手册中放一个红框:小心:此功能已损坏
    • PS:Unf。 SO 不允许删除已接受的答案。
    【解决方案2】:

    使用contains,像这样:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 2022-01-12
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 2019-12-30
      • 2020-02-13
      相关资源
      最近更新 更多