jeudi 1 juillet 2021

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 key/value from dictionary ---
        --- update json object ---

result should look like:

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

Aucun commentaire:

Enregistrer un commentaire