【问题标题】:Reduce array of dicts based on key which is a dict根据作为字典的键减少字典数组
【发布时间】:2020-11-09 05:41:34
【问题描述】:

我正在寻找一个 jq 表达式,它可以通过在“标签”上分组来减少 json。我希望输出有一个共享相同标签的目标列表。

我尝试使用 group_by 和 reduce 的一些组合,但无法得到我想要的。

输入:

[{
      "targets": [
        "host1"
      ],
      "labels": {
        "platform": "VMware",
        "os": "Windows",
        "datacenter": "dc1",
        "environment": "Production"
      }
    },{
      "targets": [
        "host2"
      ],
      "labels": {
        "platform": "VMware",
        "os": "Windows",
        "datacenter": "dc1",
        "environment": "Production"
      }
    },
    {
      "targets": [
             "host3"
      ],
      "labels": {
        "platform": "VMware",
        "os": "Windows",
        "datacenter": "dc2",
        "environment": "Production"
      }
    }
]

输出:

[{
      "targets": [
        "host1",
        "host2"
      ],
      "labels": {
        "platform": "VMware",
        "os": "Windows",
        "datacenter": "dc1",
        "environment": "Production"
      }
    },
{
      "targets": [
        "host3",
      ],
      "labels": {
        "platform": "VMware",
        "os": "Windows",
        "datacenter": "dc2",
        "environment": "Production"
      }
    }
]

P.S 示例输入没有“标签”中的所有键,并且该列表可能会有所不同。

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。
  • 通过group_by and reduce发布你说过你尝试过的尝试

标签: python json group-by aggregate jq


【解决方案1】:

如果您的要求更清晰,尤其是如果您的示例满足mcve 准则,这将很有帮助。但是,以下查询确实符合您的规范的一种解释:

group_by(.labels)
| map( { labels: (.[0].labels),
         targets: (map(.targets)|add)} )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2012-12-19
    • 2021-12-28
    • 2021-04-15
    相关资源
    最近更新 更多