在 Pydantic 的 JSON 方法中,字符编码不正确(Python)

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

Incorrect encoding cyrillic symbols in Pydantic json method (Python)

问题

以下是您要翻译的内容:

"问题的简单示例如下:

from pydantic import BaseModel

class City(BaseModel):
    name: str

city = City(name="Город")
print(city)  # name='Город'
print(city.json())  # {"name": "\u0413\u043e\u0440\u043e\u0434"}

我的系统信息:

  • Windows 11
  • Python 3.11.3
  • Pydantic 1.10.7
  • 文件 .py 的编码是 UTF-8

无论使用哪种 chcp 选项(控制台编码):866、1251、65001,问题仍然存在。如果我尝试将 json() 输出写入 txt 文件,输出仍然是相同的 \u0413\u043e\u0440\u043e\u0434。如果您能帮助我解决根本问题,我将不胜感激。我希望这段代码能够输出带有正确西里尔字母符号的纯 JSON。

我尝试过:

  • 更改 chcp 选项
  • 更改 Windows 语言设置
  • 更改 .py 文件编码
  • 重新安装 Python"
英文:

Simple example of the problem is given below:

from pydantic import BaseModel

class City(BaseModel):
    name: str

city = City(name="Город")
print(city)  # name='Город'
print(city.json())  # {"name": "\u0413\u043e\u0440\u043e\u0434"}

My system info:

  • Windows 11
  • Python 3.11.3
  • Pydantic 1.10.7
  • File .py encoding is UTF-8

Problem remains with any chcp option (console encoding): 866, 1251, 65001. If I try to write json() output into txt file, the output is same \u0413\u043e\u0440\u043e\u0434. I would really appreciate if you could help me to fix the root problem. I want this code to output pure json with proper cyrillic symbols.

I've tried:

  • Change chcp option
  • Change Windows language settings
  • Change .py file encoding
  • Reinstalled Python

答案1

得分: 2

Python的JSON模块试图保持所有JSON输出在ASCII范围内,不包含任何西里尔字符。

您可以通过使用ensure_ascii=False来关闭此设置:

print(city.json(ensure_ascii=False))

输出:

{"name": "Город"}

请注意,一些JSON解析器可能无法读取此文件。

如果您想要使用代码页866而不是UTF-8输出此字符串,您可能需要以下代码,以将字符串从Python的str类型编码为bytes类型:

city.json(ensure_ascii=False).encode('cp866')

请注意,cp866代表代码页866。

英文:

Python's JSON module tries to keep all JSON output within ASCII, which doesn't contain any cyrillic characters.

You can turn off this setting with ensure_ascii=False:

print(city.json(ensure_ascii=False))

Output:

{"name": "Город"}

Note that some JSON parsers might not be able to read this file.

If you want to output this string using codepage 866 instead of UTF-8, you might need this code, in order to encode the string from Python's str type into a bytes type:

city.json(ensure_ascii=False).encode('cp866')

Note that cp866 stands for Code Page 866.

huangapple
  • 本文由 发表于 2023年5月7日 04:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191078.html
匿名

发表评论

匿名网友

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

确定