我的JSON文件如下所示
{
"PersonA": {
"Age": "35",
"Place": "Berlin",
"cars": ["Ford", "BMW", "Fiat"]
},
"PersonB": {
"Age": "45",
"Cars": ["Kia", "Ford"]
},
"PersonC": {
"Age": "55",
"Place": "London"
}
}
我正在尝试更新这个json上的某些条目,例如,将Place
的PersonB
设置为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'
应该是这样的:
字典确实没有append方法。只有列表可以
或者使用Python 3,您可以执行以下操作:
^{} 是类型
list
的方法,而不是dict
。始终确保查看完整的方法签名,以查看方法属于什么类型相反,我们可以使用^{} :
并在代码中使用此方法,如下所示:
这给出了预期的结果:
相关问题 更多 >
编程相关推荐