gpt4 book ai didi

Python JSON 添加键值对

转载 作者:行者123 更新时间:2023-12-02 14:55:40 24 4
gpt4 key购买 nike

我正在尝试将键值对添加到现有的 JSON 文件中。我能够连接到父标签,如何为子项添加值(value)?

JSON 文件:

{
"students": [
{
"name": "Hendrick"
},
{
"name": "Mikey"
}
]
}

代码:

import json

with open("input.json") as json_file:
json_decoded = json.load(json_file)

json_decoded['country'] = 'UK'

with open("output.json", 'w') as json_file:
for d in json_decoded[students]:
json.dump(json_decoded, json_file)

预期结果:

{
"students": [
{
"name": "Hendrick",
"country": "UK"
},
{
"name": "Mikey",
"country": "UK"
}
]
}

最佳答案

您可以执行以下操作以按照您想要的方式操作 dict:

for s in json_decoded['students']:
s['country'] = 'UK'

json_decoded['students'] 是字典的列表,您可以简单地循环迭代和更新。现在您可以转储整个对象:

with open("output.json", 'w') as json_file:
json.dump(json_decoded, json_file)

关于Python JSON 添加键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53043241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com