如何向从文件检索的JSON数据中添加keyvalue?

2024-09-27 00:54:15 发布

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

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

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)

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

从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

你能行

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

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

如果您想添加多个键/值对,那么这一方法非常有效

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

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

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

相关问题 更多 >

    热门问题