Python3加载JSON文件时抛出ASCII编码错误求助
Hey there! I totally get how frustrating it is when code works fine in Python2 but breaks in Python3, especially after hours of searching. Let's break down what's going on here and fix that UnicodeEncodeError.
The Root Cause
Your code correctly reads the JSON file with UTF-8 encoding, but the error happens when you try to print(d). Here's why:
- In Python3, strings are Unicode by default. When you print them, Python tries to encode them using your terminal's default output encoding. If that default is set to ASCII (common in some older terminal setups or Windows CMD environments), any non-ASCII characters in your JSON data will trigger this error—since ASCII can't handle those characters.
Quick Fixes to Try
1. Reconfigure Standard Output (Python 3.7+)
This is the cleanest solution for newer Python versions. We'll explicitly set sys.stdout to use UTF-8 encoding:
import json, sys # Set stdout to use UTF-8 encoding sys.stdout.reconfigure(encoding='utf-8') with open('2689364.json', 'r', encoding='utf-8') as json_data: d = json.load(json_data) print(d)
2. For Older Python3 Versions (<3.7)
If you're stuck on an older Python3 release, use codecs to wrap stdout:
import json, sys import codecs # Redirect stdout to use UTF-8 sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer) with open('2689364.json', 'r', encoding='utf-8') as json_data: d = json.load(json_data) print(d)
3. Encode the Output Manually
Another approach is to convert the JSON data to a UTF-8 encoded string before printing:
import json with open('2689364.json', 'r', encoding='utf-8') as json_data: d = json.load(json_data) # Convert to UTF-8 string before printing print(str(d).encode('utf-8').decode('utf-8'))
Bonus: Check Your Terminal Encoding
Sometimes the issue is just your terminal's default encoding.
- On Linux/macOS: Run
echo $LANGto check—you want something likeen_US.UTF-8. - On Windows: Run
chcpin CMD—switch to UTF-8 withchcp 65001.
Setting your terminal to use UTF-8 can often resolve this without changing your code!
内容的提问来源于stack exchange,提问作者John Taylor

