我是Python新手,正在使用JSON数据。我想从一个文件中检索JSON数据,并在该数据中添加一个JSON键值“动态”
也就是说,我的json_file
包含如下所示的JSON数据:
{"key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
我想将"ADDED_KEY": "ADDED_VALUE"
键值部分添加到上述数据中,以便在脚本中使用以下JSON:
{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
为了实现上述目标,我正在尝试写以下内容:
import json
json_data = open(json_file)
json_decoded = json.load(json_data)
# What I have to make here?!
json_data.close()
你的
json_decoded
对象是一个Python字典;您只需将密钥添加到该文件中,然后重新编码并重写该文件:我在这里使用openfile对象作为上下文管理器(使用
with
语句),因此Python在完成时自动关闭文件从Json.loads()返回的Json的行为与本机python列表/字典类似:
有关更多信息,请查看the official doc
你能行
或
如果您想添加多个键/值对,那么这一方法非常有效
当然,您可能需要首先检查添加的密钥是否存在,这取决于您的需要
我想你可能想把数据保存回文件中
相关问题 更多 >
编程相关推荐