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

Python读取UTF-8编码JSON文件时中文乱码,求解决方案?

解决Python读取含中文JSON文件时乱码的问题

问题分析

你遇到的乱码问题大概率是因为JSON文件的实际编码并非UTF-8(比如繁体中文常用的Big5编码),即使指定utf-8或utf-8-sig读取也无法正确解析。


修复步骤

1. 检测JSON文件的实际编码

先用chardet库检测文件的真实编码:

  • 先安装chardet:
    pip install chardet
    
  • 编写检测代码:
    import chardet
    
    with open('a.json', 'rb') as f:
        detect_result = chardet.detect(f.read())
        print(detect_result)
    
    运行后会输出类似结果:
    {'encoding': 'Big5', 'confidence': 0.99, 'language': 'Chinese'}
    
    其中encoding字段就是文件的实际编码。

2. 使用正确编码读取文件

将代码中的encoding参数替换为检测到的编码(比如Big5):

import json

with open('a.json', 'r', encoding='Big5') as f:
    data = json.load(f)
    # 用json.dumps确保中文正常输出
    print(json.dumps(data, ensure_ascii=False))

3. 终端显示兼容处理(可选)

如果读取后终端仍乱码,可强制适配终端编码输出:

import json
import sys

with open('a.json', 'r', encoding='Big5') as f:
    data = json.load(f)
    output = json.dumps(data, ensure_ascii=False)
    print(output.encode(sys.stdout.encoding, errors='replace').decode(sys.stdout.encoding))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:12:02