0

I have a list of computers in an array. I would like to aggregate entries with identical IP addresses and create an array called data and append the duplicates there. Below is an example of the input and desired output. I have tried a couple different options, but can't find a solution.

Input

[
    {
        "name": "computera",
        "Computer_Name": "computera",
        "Serial_Number": "computera",
        "IP_Address": "8.8.8.8"
    },
    {
        "name": "computerb",
        "Computer_Name": "computerb",
        "Serial_Number": "computerb",
        "IP_Address": "8.8.8.8"
    },
    {
        "name": "computerc",
        "Computer_Name": "computerc",
        "Serial_Number": "computerc",
        "IP_Address": "1.2.3.4"
    }
]

Desired output

{
    "ip": "8.8.8.8",
    "data": [
        {
            "name": "computera",
            "Computer_Name": "computera",
            "Serial_Number": "computera",
            "IP_Address": "8.8.8.8"
        },
        {
            "name": "computerb",
            "Computer_Name": "computerb",
            "Serial_Number": "computerb",
            "IP_Address": "8.8.8.8"
        }
    ]
}
{
    "ip": "1.2.3.4",
    "data": [
        {
            "name": "computerc",
            "Computer_Name": "computerc",
            "Serial_Number": "computerc",
            "IP_Address": "1.2.3.4"
        }
    ]
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
mo1090
  • 15
  • 4
  • def group_computers_by_ip(computers): grouped_computers = {} for computer in computers: ip_address = computer["IP_Address"] if ip_address in grouped_computers: grouped_computers[ip_address].append(computer) else: grouped_computers[ip_address] = [computer] return grouped_computers – Golden Lion Aug 24 '23 at 20:35
  • Thanks. This groups by IP address and is very similar to the link below, but it doesn't create the needed key 'ip'. https://stackoverflow.com/questions/45404154/find-duplicates-in-json-using-python – mo1090 Aug 30 '23 at 18:30

0 Answers0