Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating/Appending to json (nested) in python

My JSON file is shown below

{
    "PersonA": {
        "Age": "35",
        "Place": "Berlin",
        "cars": ["Ford", "BMW", "Fiat"]
    },

    "PersonB": {
        "Age": "45",
        "Cars": ["Kia", "Ford"]
    },

    "PersonC": {
        "Age": "55",
        "Place": "London"
    }
}

I'm trying to update certain entries on this json E.g. set Place for PersonB to Rome similarly for PersonC update cars with an array ["Hyundai", "Ford"]`

What I have done until now is

import json

key1 ='PersonB'
key2 = 'PersonC'
filePath = "resources/test.json"
with open(filePath, encoding='utf-8') as jsonFile:
    jsonData = json.load(jsonFile)
    print(jsonData)

PersonBUpdate = {"Place" : "Rome"}
PersonCUpdate = {"cars" : ["Hyundai", "Ford"]}

jsonData[key1].append(PersonBUpdate)
jsonData[key2].append(PersonCUpdate)
print(jsonData)

It throws an error.

AttributeError: 'dict' object has no attribute 'append'
like image 604
Betafish Avatar asked May 22 '26 11:05

Betafish


2 Answers

It should be like this:

jsonData['Person1']['Place'] = 'Rome'

Dictionaries indeed do not have an append method. Only lists do.

Or with Python 3 you can do this:

jsonData['Person1'].update(PersonBUpdate)
like image 105
Orestis Zekai Avatar answered May 25 '26 01:05

Orestis Zekai


list.append is a method for type list, not dict. Always make sure to look at the full method signature to see what type a method belongs to.

Instead we can use dict.update:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

And use this method in your code like this:

jsonData[key1].update(PersonBUpdate)
jsonData[key2].update(PersonCUpdate)

Which gives the expected result:

{'PersonA': {'Age': '35', 'Place': 'Berlin', 'cars': ['Ford', 'BMW', 'Fiat']}, 'PersonB': {'Age': '45', 'Cars': ['Kia', 'Ford'], 'Place': 'Rome'}, 'PersonC': {'Age': '55', 'Place': 'London', 'cars': ['Hyundai', 'Ford']}}
like image 41
RoadRunner Avatar answered May 25 '26 02:05

RoadRunner