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

Python使用open(encoding='utf8')读取JSON仍显示Unicode转义符如何解决

解决方案

你当前代码直接读取原始文本未做JSON解析,\uXXXX是JSON规范的转义格式,Python读取普通文本时不会自动处理这类转义,需使用Python内置的json模块处理:

读取输出的正确实现

import json

with open("test.json", encoding='utf-8') as in_data:
    for line in in_data:
        # 解析每行JSON字符串,自动转换Unicode转义序列
        parsed_data = json.loads(line.strip())
        # 输出时设置ensure_ascii=False,直接显示非ASCII字符
        print(json.dumps(parsed_data, ensure_ascii=False))

运行上述代码即可得到你预期的输出结果。

写入JSON文件时避免Unicode转义的方法

如果后续需要写入JSON文件也不生成转义序列,写入时添加ensure_ascii=False参数即可:

import json

test_data = {"A":"ณ", "B":"คุ", "C":"ของ"}
with open("new_test.json", "w", encoding="utf-8") as out_file:
    json.dump(test_data, out_file, ensure_ascii=False, indent=2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:24:03