如何在使用Python从文件中检索的JSON数据中添加键值? [英] How to add a key-value to JSON data retrieved from a file with Python?

查看:673
本文介绍了如何在使用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.

这篇关于如何在使用Python从文件中检索的JSON数据中添加键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆