You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向已存在的JSON对象添加数据且不覆盖原有内容

问题解决思路与代码示例

1. 解决json.loads()的报错问题

json.loads()的作用是把JSON格式的字符串转换成Python字典/列表,而你定义的json_obj本身已经是Python字典了,直接调用这个方法必然抛出TypeError。你不需要用这个方法,直接对字典进行操作即可。

2. 修正最终数据结构的误区

你想要的最终格式是无效的JSON语法——字典不能直接嵌套字典作为元素(字典的键必须是字符串)。正确的做法是用**列表(对应JSON数组)**来存储多条数据,每条数据是一个独立的字典。正确的目标结构应为:

[
    {
        "text": "test text",
        "created_at": "some date",
        "entity": "most_common_entity",
        "username": "someuser",
        "tweet_id": "coolid",
        "hashtags": "#coolndat"
    },
    {
        "text": "Text two",
        "created_at": "12/5/3042",
        "entity": "ORG",
        "username": "cooluser3",
        "tweet_id": "nice",
        "hashtags": "#verysickhashtag"
    }
]

3. 实现数据追加的代码示例

步骤1:初始化存储容器

不要用单个字典,而是用列表来存放所有数据,把初始数据作为列表的第一个元素:

# 函数外初始化存储所有数据的列表
data_list = [
    {
        "text": "test text",
        "created_at": "some date",
        "entity": "most_common_entity",
        "username": "someuser",
        "tweet_id": "coolid",
        "hashtags": "#coolndat"
    }
]

步骤2:函数内添加新数据

在函数中创建新的字典,填入收集到的数据,然后追加到列表中(不会覆盖原有数据):

# 假设函数内已获取到row和most_common_entity
def add_new_data(row, most_common_entity):
    # 构造新的数据字典
    new_item = {
        "text": row["text"],
        "created_at": row["created_at"],
        "entity": most_common_entity,
        "username": row["username"],
        "tweet_id": row["id"],  # 修正笔误:tweets_id -> tweet_id,保持键名与初始数据一致
        "hashtags": row["hashtags"]
    }
    # 追加到列表,不会覆盖原有数据
    data_list.append(new_item)

步骤3:转换为JSON字符串(可选)

如果需要把整个数据列表转换成JSON格式的字符串,使用json.dumps():

import json
# 转换为带缩进的JSON字符串,方便阅读
json_result = json.dumps(data_list, indent=4)
print(json_result)

内容的提问来源于stack exchange,提问作者Roald Andre Kvarv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 14:45:25