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

Python修改JSON文件中嵌套字典时整体内容被覆盖如何解决

问题原因

你的代码存在两处逻辑错误:

  • 读取JSON时直接提取了keys对应的子字典,没有保留JSON文件的完整根结构
  • 写入文件时只把计算得到的数值序列化写入,自然会覆盖掉原文件的所有内容

修正后的代码

import json
async def Con_Manage(keys):
    try:
        # 读取完整JSON根结构
        with open('keys.json', 'r') as config_file:
            full_config = json.load(config_file)
        # 修改指定嵌套字段的值
        full_config[keys]["curCons"] += 1
        # 将完整结构写回文件,indent参数可保留格式化缩进方便阅读
        with open('keys.json', 'w') as config_file:
            json.dump(full_config, config_file, indent=4)
        return True
    except Exception:
        return False

内容的提问来源于stack exchange,提问作者KeratinThaSkeed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:15:01