我是Python新手,我正在使用JSON数据。我想从一个文件中检索JSON数据,并在该数据中添加一个JSON键值“动态”。
也就是说,myjson_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字典;您只需向其中添加密钥,然后重新编码并重写文件:我在这里使用open file对象作为上下文管理器(使用
with
语句),这样Python在完成时会自动关闭文件。你可以的
或者
如果您想添加多个键/值对,那么这个方法很好地工作。
当然,您可能需要首先检查是否存在添加的密钥-这取决于您的需要。
我想你可能想把数据保存回文件
从Json.loads()返回的Json的行为与本地python列表/字典类似:
更多信息请查看the official doc
相关问题 更多 >
编程相关推荐