[英]Python JSON add Key-Value pair
I'm trying to add key value pairs into the existing JSON file. 我正在尝试将键值对添加到现有的JSON文件中。 I am able to concatenate to the parent label, How to add value to the child items?
我可以连接到父标签,如何为子项目增加价值?
JSON file: JSON文件:
{
"students": [
{
"name": "Hendrick"
},
{
"name": "Mikey"
}
]
}
Code: 码:
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)
Expected Results: 预期成绩:
{
"students": [
{
"name": "Hendrick",
"country": "UK"
},
{
"name": "Mikey",
"country": "UK"
}
]
}
You can do the following in order to manipulate the dict
the way you want: 您可以执行以下操作以按所需方式操作
dict
:
for s in json_decoded['students']:
s['country'] = 'UK'
json_decoded['students']
is a list
of dictionaries that you can simply iterate and update in a loop. json_decoded['students']
是字典的list
,您可以简单地循环访问和更新。 Now you can dump the entire object: 现在您可以转储整个对象:
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)
Moved writing to output file inside to first with
segment. 将写入到输出文件的写入移到了
with
段的第一个。 Issue with earlier implemenation is that json_decoded
will not be instantiated if opening of input.json
fails. 较早实现的问题是,如果打开
input.json
失败,则不会实例化json_decoded
。 And hence, writing to output will raise an exception - NameError: name 'json_decoded' is not defined
因此,写入输出将引发异常
NameError: name 'json_decoded' is not defined
This gives [None, None]
but update the dict: 这给出了
[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.