首页 > 解决方案 > 根据作为字典的键减少字典数组

问题描述

我正在寻找一个 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"
      }
    }
]

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

标签: pythonjsongroup-byaggregatejq

解决方案


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

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

推荐阅读