json 加载失败并出现 UnicodeEncodeError
json loads fails with UnicodeEncodeError
以下代码在 docker 容器中给出 UnicodeEncodeError 错误 ubuntu 18:
Python 3.6.9 (default, Apr 18 2020, 01:56:04)
import json
text = b'["Chauss\u00e9e de Tubize"]'
test = json.loads(text)
test
['Chauss\xe9e de Tubize'] # on other server this correctly results into ['Chaussée de Tubize']
print(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 8: ordinal not in range(128)
奇怪的是,这段代码片段在具有相同 python 版本 (3.6.9) 的 ubuntu 服务器上运行。
我不明白为什么 json 模块试图编码为 ascii。我认为自 python3 以来,标准是使用 unicode utf-8。
不,您的错误与 JSON 或 Python3 的编码无关。您的错误与您的控制台字符集有关。您的区域设置有 ASCII 字符集,因此 python 无法打印您的字符串。
您应该转换并指定如何处理编码错误,在使用 print
时也是如此。
也许你应该 install/use 一个支持 UTF-8 的语言环境。
以下代码在 docker 容器中给出 UnicodeEncodeError 错误 ubuntu 18:
Python 3.6.9 (default, Apr 18 2020, 01:56:04)
import json
text = b'["Chauss\u00e9e de Tubize"]'
test = json.loads(text)
test
['Chauss\xe9e de Tubize'] # on other server this correctly results into ['Chaussée de Tubize']
print(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 8: ordinal not in range(128)
奇怪的是,这段代码片段在具有相同 python 版本 (3.6.9) 的 ubuntu 服务器上运行。 我不明白为什么 json 模块试图编码为 ascii。我认为自 python3 以来,标准是使用 unicode utf-8。
不,您的错误与 JSON 或 Python3 的编码无关。您的错误与您的控制台字符集有关。您的区域设置有 ASCII 字符集,因此 python 无法打印您的字符串。
您应该转换并指定如何处理编码错误,在使用 print
时也是如此。
也许你应该 install/use 一个支持 UTF-8 的语言环境。