【发布时间】:2019-01-30 01:19:44
【问题描述】:
假设我有一个 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}}]}]
我想遍历这个列表并拥有一个“主”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"
【问题讨论】:
-
我不知道,但可能是因为有人撤销了他/她的投票。
标签: python json python-3.x iteration updates