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

Python3加载JSON文件时抛出ASCII编码错误求助

Fixing UnicodeEncodeError in Python3 for JSON Print Output

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 $LANG to check—you want something like en_US.UTF-8.
  • On Windows: Run chcp in CMD—switch to UTF-8 with chcp 65001.

Setting your terminal to use UTF-8 can often resolve this without changing your code!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:49:28