可以说我有一个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)
这里的问题是我不想每次新迭代都“更新” masterJson对象。本质上,子对象“名称”和“日期”将始终相同。我想做的是仅添加到“功能”子对象列表中,以便在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"
答案 0 :(得分:1)
此循环位在masterJson
字典中添加了功能部件。
tempList = []
masterJson = {}
masterJson['Name'] = list[0]['Name']
masterJson['Date'] = list[0]['Date']
for item in list:
tempList.extend(item['features'])
masterJson['features']=tempList
在使用此部分之前,将Name
和Date
部分添加到masterJson
字典中,您将具有所需的结构。
tempList
是一个临时列表,用于保存不同的features
字典。
欢呼。