[英]How to add a key-value pair in dictionary for dumping data in JSON format in python?
[英]Python JSON add Key-Value pair
我正在尝试将键值对添加到现有的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)
import json
with open("input.json", 'r') as json_file:
json_decoded = json.load(json_file)
for element in json_decoded['students']:
element['country'] = 'UK'
with open("output.json", 'w') as json_out_file:
json.dump(json_decoded, json_out_file)
将写入到输出文件的写入移到了with
段的第一个。 较早实现的问题是,如果打开input.json
失败,则不会实例化json_decoded
。 因此,写入输出将引发异常NameError: name 'json_decoded' is not defined
这给出了[None, None]
但更新了dict:
a = {'students': [{'name': 'Hendrick'}, {'name': 'Mikey'}]}
[i.update({'country':'UK'}) for i in a['students']]
print(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.