如何在使用Python从文件中检索的JSON数据中添加键值?

问题描述:

我是Python的新手,并且正在使用JSON数据.我想从文件中检索JSON数据,然后即时"将JSON键值添加到该数据中.

I am new to Python and I am playing with JSON data. I would like to retrieve the JSON data from a file and add to that data a JSON key-value "on the fly".

也就是说,我的json_file包含JSON数据,如下所示:

That is, my json_file contains JSON data as-like the following:

{"key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}

我想将"ADDED_KEY": "ADDED_VALUE"键值部分添加到上述数据中,以便在脚本中使用以下JSON:

I would like to add the "ADDED_KEY": "ADDED_VALUE" key-value part to the above data so to use the following JSON in my script:

{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}

为了达到上述目的,我正在尝试编写如下内容:

I am trying to write something as-like the following in order to accomplish the above:

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字典;您只需在其中添加密钥,然后重新编码并重写文件即可:

Your json_decoded object is a Python dictionary; you can simply add your key to that, then re-encode and rewrite the file:

import json

with open(json_file) as json_file:
    json_decoded = json.load(json_file)

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

with open(json_file, 'w') as json_file:
    json.dump(json_decoded, json_file)

我在这里使用打开的文件对象作为上下文管理器(使用with语句),因此Python完成后会自动关闭文件.

I used the open file objects as context managers here (with the with statement) so Python automatically closes the file when done.