Replace object in json with another json file using python
Question: I currently have two json files that I need to combine using python.
Essentially I want to replace the choices array in file 1 with the array in
file 2 using python. How do I go about doing this? File 1 is:

    
    
    {
        "choice_list": {
            "name": "Boston Street Names",
            "choices":[ {"value": "127906", "label": "DAVIS STREET"},
                        {"value": "129909", "label": "NORTH QUINCY STREET" },
                        { "value": "134194", "label": "ADAMS STREET" }] 
         } 
    }
    

File 2 is:

    
    
    [{"value": "134484", "label": "PRISCILLA ALDEN ROAD"},
     {"value": "134487", "label": "VAN BUREN DRIVE"}]
    


Answer: Use the native python JSON library:

    
    
    import json
    json1 = '{\
        "choice_list": {\
            "name": "Boston Street Names",\
            "choices":[ {"value": "127906", "label": "DAVIS STREET"},\
                        {"value": "129909", "label": "NORTH QUINCY STREET" },\
                        { "value": "134194", "label": "ADAMS STREET" }]\
         } \
    }'
    
    json2 = '[{"value": "134484", "label": "PRISCILLA ALDEN ROAD"},\
     {"value": "134487", "label": "VAN BUREN DRIVE"}]'
    
    res = json.loads(json1)
    res['choice_list']['choices'] = json.loads(json2)
    print json.dumps(res)
    

Results in:

    
    
    {"choice_list":
        {"name": "Boston Street Names",
         "choices":
             [{"value": "134484","label": "PRISCILLA ALDEN ROAD"},
              {"value": "134487", "label": "VAN BUREN DRIVE"}]
        }
    }
    

The loads method takes in a JSON string and converts it to a python dictionary
object (with all keys as unicode). You can then load the other JSON object,
reference to the key you want to replace, and assign it. Then you just convert
back to a JSON string.

