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

2024-09-27 04:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

Tags: 数据keyjsonaddeddatafile键值key1
3条回答

您的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)

我在这里使用open file对象作为上下文管理器(使用with语句),这样Python在完成时会自动关闭文件。

你可以的

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

或者

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

如果您想添加多个键/值对,那么这个方法很好地工作。

当然,您可能需要首先检查是否存在添加的密钥-这取决于您的需要。

我想你可能想把数据保存回文件

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

从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!

更多信息请查看the official doc

相关问题 更多 >

    热门问题