遍历目录及子目录加载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

