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

Python加载JSON文件后特殊字符乱码,如何保留原始内容?

解决JSON文件加载后DataFrame出现乱码的问题

问题场景

我有如下内容的JSON文件:

{"title": "Item number - This is of no use"}
{"title": "Did you find Ram's sale application?"}

使用以下代码加载读取:

with open(data, 'r', encoding='utf8') as file:
        test = json.load(file)
df = pd.DataFrame.from_dict(test)

加载后DataFrame中的内容出现乱码:

Item number û This is of no use
Did you find RamÆs sale application?

我尝试移除双引号和单引号,但问题仍未解决,请问如何避免乱码并保留原始内容?

解决方案

乱码的核心原因是你指定的utf8编码与文件的实际编码不匹配,比如文件可能是Windows-1252、ISO-8859-1这类编码。按以下步骤解决:

  • 第一步:检测文件的真实编码
    使用chardet库检测文件编码,先安装库(如果没装):pip install chardet,然后运行代码:

    import chardet
    
    with open(data, 'rb') as file:
        result = chardet.detect(file.read())
    print(result)
    

    输出会包含编码类型和置信度,比如{'encoding': 'Windows-1252', 'confidence': 0.73}。

  • 第二步:用真实编码重新读取文件
    把代码中的encoding参数替换成检测到的编码,比如检测到是Windows-1252,代码修改为:

    import json
    import pandas as pd
    
    with open(data, 'r', encoding='Windows-1252') as file:
        test = json.load(file)
    df = pd.DataFrame.from_dict(test)
    

    这样就能正确读取原始内容,不会出现乱码。

  • 临时替代方案(不推荐)
    如果暂时无法确定真实编码,可以添加errors='replace'参数,将无法识别的字符替换为占位符,但可能丢失部分信息:

    with open(data, 'r', encoding='utf8', errors='replace') as file:
        test = json.load(file)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:45:38