【发布时间】:2020-08-05 15:05:58
【问题描述】:
我的 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 使用数组["Hyundai", "Ford"]`
到目前为止我所做的是
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'
【问题讨论】:
-
好吧,就是这样:
dicts 没有append方法。但是,有update方法
标签: python json list dictionary