简体   繁体   中英

Reduce array of dicts based on key which is a dict

I'm looking for a jq expression that can reduce the json by grouping them on "labels".I want the output to have a list of targets that share the same labels.

I tried using some combinations of group_by and reduce but wasn't able to get what I wanted.

INPUT:

[{
      "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"
      }
    }
]

OUTPUT:

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

PS The sample input doesn't have all the keys in "labels" and that list can vary .

It would be helpful if your requirements were clearer, and in particular if your example satisfied the mcve guidelines. The following query does, however, meet one interpretation of your specification:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM