python - Python JSON 添加键值对
问题描述
我正在尝试将键值对添加到现有的 JSON 文件中。我能够连接到父标签,如何为子项目增加价值?
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']
是一个list
字典,您可以简单地循环迭代和更新。现在您可以转储整个对象:
with open("output.json", 'w') as json_file:
json.dump(json_decoded, json_file)
推荐阅读
- python - pandas Sqlite 和重采样错误仅对 DatetimeIndex 有效
- reactjs - 如何从路由对象制作受保护的路由?
- python - 有什么方法可以将另一行中的名称显示为与熊猫中的 id 对应的新列?
- c# - 以编程方式将精灵分配给新图像
- jquery - 仅针对 1 个元素的客户端表单有效性检查
- azure - 带有私有 Api 后端的 Azure WebApp
- python - 如何根据熊猫数据框中内容的某些条件删除行
- python - Conda-build 检测相对基本项目的冲突
- python - socket.connect 抛出 TypeError:需要一个类似字节的对象,而不是“元组”
- c# - C#如何在继承的类中使用事件