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

遍历目录及子目录加载JSON文件时触发JSONDecodeError

遍历目录及子目录加载JSON文件时出现JSONDecodeError

错误信息

json_data = json.load(json_file)
File "/usr/lib/python3.9/json/init.py", line 293, in load
return loads(fp.read(),
File "/usr/lib/python3.9/json/init.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.9/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)

当前代码

for root, dirs, files in os.walk(self.opt_dir_path):
    for file in files:
        json_file = open(os.path.join(root, file), 'r')
        json_data = json.load(json_file)
        print(json_data)
        json_file.close()

排查与解决方案

1. 过滤非JSON文件

os.walk会遍历目录下所有文件,包含非.json后缀的文件(比如临时文件、日志文件),这些文件内容不符合JSON格式,直接加载必然报错。修改代码只处理后缀为.json的文件:

import os
import json

for root, dirs, files in os.walk(self.opt_dir_path):
    for file in files:
        if not file.endswith('.json'):
            continue
        file_path = os.path.join(root, file)
        with open(file_path, 'r') as json_file:
            json_data = json.load(json_file)
            print(json_data)

2. 捕获并定位损坏的JSON文件

部分.json文件可能存在格式错误、内容为空或编码问题,导致解析失败。添加try-except块捕获错误,避免程序中断,同时定位问题文件:

import os
import json

for root, dirs, files in os.walk(self.opt_dir_path):
    for file in files:
        if not file.endswith('.json'):
            continue
        file_path = os.path.join(root, file)
        try:
            with open(file_path, 'r') as json_file:
                json_data = json.load(json_file)
                print(json_data)
        except json.JSONDecodeError as e:
            print(f"解析失败: {file_path} | 错误详情: {e}")

3. 处理文件编码问题

如果JSON文件不是UTF-8编码(比如GBK、UTF-8带BOM),可能导致隐式解析错误。指定编码打开文件:

with open(file_path, 'r', encoding='utf-8-sig') as json_file:
    json_data = json.load(json_file)

4. 跳过空文件

错误提示Expecting value也可能是文件为空导致的,加载前检查文件大小:

if os.path.getsize(file_path) == 0:
    print(f"跳过空文件: {file_path}")
    continue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:22:54