如何向从文件中获取的JSON数据添加键值对?

40 投票
3 回答
140465 浏览
提问于 2025-04-18 02:59

我刚开始学习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()

相关问题:

3 个回答

9

你可以这样做:

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

或者

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

如果你想添加多个键值对,这种方法效果很好。

当然,你可能想先检查一下 ADDED_KEY 是否存在,这要看你的需求。

而且我猜你可能还想把这些数据保存回文件中。

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

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

想了解更多信息,可以查看 官方文档

43

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

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

撰写回答