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'
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)
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']}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With