无法在Python中使用UTF-8编码读取JSON文件时显示中文字符,是否有解决方案?

huangapple go评论70阅读模式
英文:

Can't display Chinese characters in Python when reading a JSON file with UTF-8 encoding, any solutions?

问题

我正在处理一个包含中文字符的 JSON 文件。我尝试在我的机器上使用 Python 读取它,但是中文字符无法正确显示。以下是 JSON 文件(a.json):

{
  "squadName": "哈囉",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true
}

以下是我的代码:

import json

storage = []
with open('a.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    print(data)

以下是输出结果:

{'squadName': '���o', 'homeTown': 'Metro City', 'formed': 2016, 'secretBase': 'Super tower', 'active': True}

除了中文字符之外,一切正常。有人知道如何修复吗?

我已经搜索了很多解决方案,我还将 'encoding' 参数设置为 'utf-8' 或 'utf-8-sig',但仍然无法正常工作。

英文:

I am working on a json file with Chinese words in it. I try to read it in my machine with Python, but the Chinese characters just can't be correctly displayed. Here is the json file(a.json):

{
  "squadName": "哈囉",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true
}

Here is my code:

import json

storage = []
with open('a.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    print(data)

Here is the output:

{'squadName': '���o', 'homeTown': 'Metro City', 'formed': 2016, 'secretBase': 'Super tower', 'active': True}

Everything works properly except for the Chinese characters
Does anyone know how to fix it?

I've searched so many solutions and I also set the 'encoding' parameter to utf-8 or utf-8-sig, but it still not working.

答案1

得分: 1

你的代码运行得很好。但是,你需要确保你的输出处理程序能够正确显示这些字符。

英文:

Your code works just fine. However, you need to ensure that your output handler is capable of properly displaying these characters.

答案2

得分: 0

你不需要修复任何东西。你的代码没问题。

如下所示:

(这是Pycharm IDE)
无法在Python中使用UTF-8编码读取JSON文件时显示中文字符,是否有解决方案?

(CMD终端)
无法在Python中使用UTF-8编码读取JSON文件时显示中文字符,是否有解决方案?

英文:

Yes, you don't need to fix anything. Your code is just fine.

As you can see below:

(this is Pycharm IDE)
无法在Python中使用UTF-8编码读取JSON文件时显示中文字符,是否有解决方案?

(CMD terminal)
无法在Python中使用UTF-8编码读取JSON文件时显示中文字符,是否有解决方案?

huangapple
  • 本文由 发表于 2023年5月26日 11:45:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定