Updating a 'master' JSON object by adding

2019-06-13 15:18发布

问题:

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.