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

Python中JSON转Excel遇UnicodeDecodeError错误的解决方法

解决JSON加载时的UnicodeDecodeError问题

这个错误的核心原因是你打开JSON文件时使用了系统默认的charmap编码,而目标文件的实际编码(通常是UTF-8)与默认编码不兼容,导致特定字节无法解码。以下是几种可行的解决方法:

1. 指定UTF-8编码打开文件

UTF-8是JSON格式的标准编码,直接显式指定编码即可解决绝大多数此类问题:

import json

with open("你的JSON文件路径.json", "r", encoding="utf-8") as json_file:
    data = json.load(json_file)

2. 尝试其他常见编码(若UTF-8失效)

如果指定UTF-8仍报错,可能文件使用了其他编码(如GB2312、UTF-16等),可以逐一尝试:

# 尝试GB2312编码
with open("你的JSON文件路径.json", "r", encoding="gb2312") as json_file:
    data = json.load(json_file)

# 尝试UTF-16编码
with open("你的JSON文件路径.json", "r", encoding="utf-16") as json_file:
    data = json.load(json_file)

3. 忽略错误字节(临时应急方案)

若不需要保留所有特殊字符,可通过errors='ignore'参数跳过无法解码的字节,但此方法会丢失部分数据,仅建议临时使用:

with open("你的JSON文件路径.json", "r", encoding="utf-8", errors="ignore") as json_file:
    data = json.load(json_file)

4. 检测文件实际编码

如果不确定文件编码,可使用chardet库自动检测:
首先安装库:

pip install chardet

然后执行检测代码:

import chardet

with open("你的JSON文件路径.json", "rb") as f:
    detection_result = chardet.detect(f.read())

# 打印检测到的编码
print(detection_result["encoding"])

最后用检测出的编码打开文件即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:24:56