简体   繁体   中英

Append to an array inside a JSON object based on key in python

I have some JSON I'm looping through in the following format. I need to create an object for each unique primary key found in the source data and append to an array. I'm not sure how I would create the object on first encounter of the key and append to it on the next encounter. My initial attempt just creates a new object for each object in the source. Wasn't able to find an example in python only js. Source data format:

[
...
  {
    "Id": "NOT NEEDED DATA",
    "Client": {
      "Id": "KEY",
      "Name": "NOT NEEDED DATA"
    },
    "Name": "DESIRED DATAPOINT"
  },
...
]

Desired format:

[
...
    {
        "client_id": "KEY",
        "locations": ["DATA", "DATA"]
    }
...
]

pseudocode

for i in sourcedata:
    client_id = i['Client']['Id']
    location_name = i['Name']
    obj = {
        "client_id": client_id,
        "locations": [location_name]
    }
    new_array.append(obj)

You can first iterate and build a dictionary for then creating a list of dictionaries as specified in your output format.

from collections import defaultdict    

# create and populate the dictionary
d = defaultdict(list)
for i in sourcedata:
    client_id = i['Client']['Id']
    location_name = i['Name']
    d[client_id].append(location_name)

# build the result
res = [{"client_id": k, "locations": v} for k,v in d.items()]

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