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

Python编辑JSON文件出现内容重复,如何删除或阻止重复生成?

问题分析与解决

核心问题

你的代码导致JSON文件出现重复结构的原因有两个:

  • 写入文件时用了追加模式('a'):这种模式会把新内容直接追加在原文件末尾,而非替换原内容,最终导致两个完整JSON结构拼接在一起。
  • if分支未保存修改:当前只有else分支会执行文件写入,if分支修改了数据但没保存,等于白改。

另外还有个逻辑漏洞:用a in str(temp)判断tag是否存在的方式不严谨——把整个JSON转成字符串查找,可能出现误判(比如tag名称刚好出现在用户输入或回复内容里)。

修正后的代码

import json

# 读取原JSON文件
with open('test.json', 'r') as f:
    json_data = json.load(f)
    temp = json_data

tag_input = input('tag: ')

# 严谨检查tag是否存在,同时定位目标intent
tag_exists = False
target_intent = None
for intent in temp["intents"]:
    if intent["tag"] == tag_input:
        tag_exists = True
        target_intent = intent
        break

if tag_exists:
    print('tag claimed')
    user_input = input('user input: ')
    response = input('responses: ')
    target_intent["user_input"].append(user_input)
    target_intent["responses"].append(response)
else:
    user_input = input('user input: ')
    response = input('responses: ')
    new_intent = {
        "tag": tag_input,
        "user_input": [user_input],
        "responses": [response],
        "context_set": ""
    }
    temp["intents"].append(new_intent)

# 统一用写入模式覆盖原文件,保存所有修改
with open('test.json', 'w') as f:
    json.dump(temp, f, indent=4)

修改说明

  1. 文件写入模式改为'w':'w'模式会清空原文件内容,再写入修改后的完整JSON结构,彻底避免重复内容。
  2. 将写入逻辑移到分支外部:不管是修改已有tag还是新增tag,最后都会执行保存操作,确保所有修改生效。
  3. 优化tag存在性检查:遍历intents列表对比tag字段,既避免误判,还能直接定位到要修改的intent对象(之前的代码只会修改第一个intent,这也是隐藏bug)。

内容的提问来源于stack exchange,提问作者Kiyuma - san

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:05:16