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

Python加载JSON文件遇JSONDecodeError问题求助

解决JSONDecodeError: Expecting value: line 1 column 1 (char 0)问题

这个错误本质是加载的文件不符合JSON格式,结合你的代码场景,以下是具体排查和解决方法:

核心问题分析

你当前的load_combinations在文件不存在时会创建空文件,而空文件完全不符合JSON语法规则,后续加载必然触发解析错误。此外,路径匹配、文件写入的潜在问题也可能导致类似报错。

具体解决方案

1. 修复空文件初始化逻辑

修改文件创建时的逻辑,直接写入合法的空JSON对象(空字典),避免生成无效空文件:

def load_combinations(self):
    if os.path.exists('combinations.json'):
        with open('combinations.json', 'r') as f:
            self.combinations = json.load(f)
    else:
        # 初始化空字典并写入文件,保证文件内容合法
        self.combinations = {}
        with open('combinations.json', 'w') as f:
            json.dump(self.combinations, f)

2. 验证文件路径一致性

确认代码运行的工作目录与combinations.json所在目录一致,可通过以下代码打印路径验证:

import os
print("当前工作目录:", os.getcwd())
print("文件绝对路径:", os.path.abspath('combinations.json'))

如果路径不匹配,直接使用文件的绝对路径进行读写操作。

3. 优化保存代码的可靠性

你的save_combinations可以做两处优化:一是用str.join替代循环拼接字符串提升效率,二是改用w模式替代w+(w+可能因指针位置问题引发意外):

def save_combinations(self):
    toSave = {}
    for c, i in self.combinations.items():
        string = ''.join(str(u) for u in i)
        toSave[c] = string

    with open('combinations.json', 'w') as f:
        json.dump(toSave, f, indent=4)

4. 快速验证流程

  1. 删除当前存在的combinations.json文件
  2. 运行修改后的load_combinations,确认生成的文件内容是{}
  3. 调用save_combinations写入数据
  4. 再次执行加载逻辑,确认报错消失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:22:47