简体   繁体   中英

How to update json object with dictionary in python

The goal is to update a json object that contains a particular key

The json file looks like:

{
 "collection": [
{"name": "name1", "phone": "10203040"}, 
{"name": "name2", "phone": "20304050", "corporateIdentificationNumber": "1234"}, 
{"name": "name3", "phone": "30405060", "corporateIdentificationNumber": "5678"}
]}

if a json object contains the key 'corporateIdentificationNumber', then iterate through a dictonary and update 'name' and 'corporateIdentificationNumber' from dictionary. Dictionary looks like this:

dict = {"westbuilt": "4232", "Northbound": "5556"}

In other words that means that i need to update the json object with a dictionary, and whenever i am updating a json object, it should select key/value pair from dictionary, and then iterate to next key/value for next json object containing 'corporateIdentificationNumber'

Code:

r = requests.get(url="*URL*")
file = r.json()

for i in file['collection']:
    if 'corporateIdentificationNumber' in i:
        --- select next iterated key/value from dict---
        --- update json object ---

result should look like:

   {
 "collection": [
{"name": "name1", "phone": "10203040"}, 
{"name": "westbuilt", "phone": "20304050", "corporateIdentificationNumber": "4232"}, 
{"name": "Northbound", "phone": "30405060", "corporateIdentificationNumber": "5556"}
]}

I think you need to use an iterator to the items:

updates = {"westbuilt": "4232", "Northbound": "5556"}

r = requests.get(url="*URL*")
file = r.json()

items = iter(updates.items())
try:
    for i in file['collection']:
        if 'corporateIdentificationNumber' in i:
            d = next(items)
            i['name'] = d[0]
            i["corporateIdentificationNumber"] = d[1]
except StopIteration:
    pass

print(file)
json_object["corporateIdentificationNumber"] = "updated value"
file = open("your_json_file.json", "w")
json.dump(json_object, file)
file.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM