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

Python读取JSON文件遇UnicodeDecodeError:原因及解决方法

UnicodeDecodeError When Loading JSON File in Python: What’s Going On & How to Fix It

Let’s break down what’s causing this error and how to fix it step by step.

Why This Error Happens

The error you’re hitting boils down to an encoding mismatch. When you open a file without specifying an encoding, Python defaults to using your system’s native encoding—here, that’s cp1252, a Windows-specific character set. But your StreamingHistory0.json file is almost certainly saved in UTF-8 (the standard encoding for JSON files), which includes characters that cp1252 doesn’t recognize (like the 0x81 byte mentioned in the error). Python tries to decode the file with cp1252, hits a character it can’t map to a readable symbol, and throws that UnicodeDecodeError.

Fixes to Try

Since UTF-8 is the universal standard for JSON, this is the most reliable fix. Just add the encoding='utf-8' parameter to your open() call:

import json
with open('StreamingHistory0.json', encoding='utf-8') as json_file:
    history = json.load(json_file)

This tells Python to use the correct encoding to decode all Unicode characters in your streaming history file.

2. Ignore Unreadable Characters (Last Resort)

If you need a quick workaround and don’t mind losing a tiny bit of data, you can tell Python to skip characters it can’t decode with the errors='ignore' parameter. Note: This will discard the unreadable characters, so use this only if you don’t care about that specific data:

import json
with open('StreamingHistory0.json', errors='ignore') as json_file:
    history = json.load(json_file)

3. Detect the File’s Exact Encoding

If you’re unsure what encoding your file uses, use the chardet library to detect it automatically. First, install the library:

pip install chardet

Then run this code to get the encoding:

import chardet

with open('StreamingHistory0.json', 'rb') as f:
    encoding_result = chardet.detect(f.read())

print(f"Detected encoding: {encoding_result['encoding']}")

Once you have the detected encoding, plug it into your open() call (e.g., encoding='utf-16' if that’s what shows up).


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:17:42