通过向子对象添加数据来更新 'master' JSON 对象

Updating a 'master' JSON object by adding data to a subobject

假设我有一个 JSON 个对象的列表:

list = [{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 2, "Zone": "A"}, "geo": {"x": 10, "y": 20}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 3, "Zone": "D"}, "geo": {"x": 21, "y": 8}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 5, "Zone": "C"}, "geo": {"x": 15, "y": 10}}]}]

我想遍历此列表并有一个 'Master' json 对象:

masterJson = {}
for item in list:
    print(item)

这里的问题是我不想 'update' masterJson 对象与每个新的迭代。本质上,子对象 "Name" 和 "Date" 将始终相同。我想要做的是仅添加到 "features" 子对象列表,以便在 masterJson 对象中它看起来像这样:

masterJson = {"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 2, "Zone": "A"}, "geo": {"x": 10, "y": 20}}, {"attributes": {"OID": 3, "Zone": "D"}, "geo": {"x": 21, "y": 8}}, {"attributes": {"OID": 5, "Zone": "C"}, "geo": {"x": 15, "y": 10}}]}

我目前的想法是拥有类似下面的东西,但我无法让它为我工作。我该如何实现?

list = [{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 2, "Zone": "A"}, "geo": {"x": 10, "y": 20}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 3, "Zone": "D"}, "geo": {"x": 21, "y": 8}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 5, "Zone": "C"}, "geo": {"x": 15, "y": 10}}]}]
masterJson = list[0]
for item in list:
    for item["features"]:
        masterJson["features"] = (item["features"])

print(masterJson)

另一种变体:

masterJson = list[0]
for item in list:
    for k in item:
        if k not in masterJson["features"]
            masterJson["features"] = (item["features"])

print(masterJson)

注:结果好像是"features": "features"

这个循环位在 masterJson 字典中添加特征部分。

tempList = []
masterJson = {}
masterJson['Name'] = list[0]['Name']
masterJson['Date'] = list[0]['Date']
for item in list:
    tempList.extend(item['features'])
masterJson['features']=tempList

在使用这部分之前,将 NameDate 部分添加到 masterJson 字典中,您将拥有所需的结构。 tempList 是一个临时列表,用于保存不同的 features 字典。 干杯。