我的JSON文件如下所示
{
"PersonA": {
"Age": "35",
"Place": "Berlin",
"cars": ["Ford", "BMW", "Fiat"]
},
"PersonB": {
"Age": "45",
"Cars": ["Kia", "Ford"]
},
"PersonC": {
"Age": "55",
"Place": "London"
}
}
我正在尝试更新此 json 中的某些条目,例如将 PersonB
的 Place
设置为 Rome
类似地为 PersonC
更新 cars
数组 [ “现代”、“福特”]`
到目前为止我所做的是
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)
它抛出一个错误。
AttributeError: 'dict' object has no attribute 'append'
最佳答案
应该是这样的:
jsonData['Person1']['Place'] = 'Rome'
字典确实没有追加方法。只有列表可以。
或者使用 Python 3 你可以这样做:
jsonData['Person1'].update(PersonBUpdate)
关于python - 在 python 中更新/附加到 json(嵌套),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61367755/