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

也就是说,my 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", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}

为了实现上述目标,我正在try 写一些类似以下内容的内容:

import json

json_data = open(json_file)
json_decoded = json.load(json_data)

# What I have to make here?!

json_data.close()

推荐答案

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)

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

Json相关问答推荐

从JSON格式提取数据时分隔通用名称

对面的行/列进行排序时可能出现错误

当console.log返回TRUE值时,解析的JSON中的字段未定义

处理输入数据并转换为更简单的格式-PowerBI

Jolt Spec 跳过数组中的第一个元素

XSLT 3.0 Json-to-xml,json 包含 html struct

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

条件性构建/修改嵌套对象数组

如何使用SQLite Trigger将JSON对象数组转换为新记录?

使用 jq 将非统一的 json 输出转换为汇总表

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

jq搜索特定字符串并输出对应的父值

如何为包含一些固定值并可能具有其他附加值的数组字符串创建数组 json 架构

Jolt - 在同一级别添加时组合值的问题

如何使用 Kotlin + Jackson 将 JSON 反序列化为 List

使用 jq 如何用其他名称替换键的名称

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

如何判断 JSON 响应元素是否为数组?

请求返回字节,我无法解码它们

如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性