在python中更新/附加到json(嵌套)

2024-09-24 06:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我的JSON文件如下所示

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

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

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

我正在尝试更新这个json上的某些条目,例如,将PlacePersonB设置为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'

Tags: jsonageplacecarsprintkey2key1jsondata
2条回答

应该是这样的:

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

字典确实没有append方法。只有列表可以

或者使用Python 3,您可以执行以下操作:

jsonData['Person1'].update(PersonBUpdate)

^{}是类型list的方法,而不是dict。始终确保查看完整的方法签名,以查看方法属于什么类型

相反,我们可以使用^{}

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).

并在代码中使用此方法,如下所示:

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

这给出了预期的结果:

{'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']}}

相关问题 更多 >