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

倾然丶 夕夏残阳落幕 提交于 2019-12-23 05:25:34

问题


Lets say I have a list of JSON objects:

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}}]}]

I want to iterate through this list and have a single 'Master' json object:

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

The problem here is that I don't want to just 'update' the masterJson object with every new iteration. Essentially, the subobjects "Name" and "Date" will always be the same. What I want to do is add to the "features" subobject list only so that in the masterJson object it looks like this:

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}}]}

My current idea is to have something like the following, but I can't get it to quite work for me. How do I achieve this?

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)

Another variation:

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

print(masterJson)

Note: The results seem to be "features": "features"


回答1:


This loop bit adds the features part in the masterJson dict.

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

before using this part, add the Name and Date part to the masterJson dict and you will have the structure you require. tempList is a temporary list to hold the different features dict. cheers.



来源:https://stackoverflow.com/questions/51989564/updating-a-master-json-object-by-adding-data-to-a-subobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!