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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23111625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:15:45  来源:igfitidea点击:

How to add a key-value to JSON data retrieved from a file with Python?

pythonjsonfile

提问by Backo

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".

我是 Python 新手,正在处理 JSON 数据。我想从文件中检索 JSON 数据,并将 JSON 键值“动态”添加到该数据中。

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

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

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

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"键值部分添加到上述数据中,以便在我的脚本中使用以下 JSON:

{"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()

采纳答案by Martijn Pieters

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

你的json_decoded对象是一个 Python 字典;你可以简单地添加你的密钥,然后重新编码和重写文件:

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)

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

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

回答by bsoist

You can do

你可以做

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

OR

或者

json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})

which works nicely if you want to add more than one key/value pair.

如果您想添加多个键/值对,这很有效。

Of course, you may want to check for the existence of ADDED_KEY first - depends on your needs.

当然,您可能想先检查 ADDED_KEY 是否存在 - 取决于您的需要。

AND I assume you want might want to save that data back to the file

而且我假设您可能希望将该数据保存回文件

json.dump(json_decoded, open(json_file,'w'))

回答by 0xff

Json returned from json.loads() behave just like native python lists/dictionaries:

从 json.loads() 返回的 Json 行为就像原生 python 列表/字典:

import json

with open("your_json_file.txt", 'r') as f:
    data = json.loads(f.read()) #data becomes a dictionary

#do things with data here
data['ADDED_KEY'] = 'ADDED_VALUE'

#and then just write the data back on the file
with open("your_json_file.txt", 'w') as f:
    f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
#I added some options for pretty printing, play around with them!

For more info check out the official doc

有关更多信息,请查看官方文档