简体   繁体   English

根据python中的键附加到JSON对象内的数组

[英]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.我有一些 JSON 我正在以以下格式循环。 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.仅在 js 中无法在 python 中找到示例。 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()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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