【问题标题】:json loads fails with UnicodeEncodeErrorjson 加载失败并出现 UnicodeEncodeError
【发布时间】:2020-10-02 06:51:36
【问题描述】:

以下代码在使用 ubuntu 18 的 docker 容器中给出 UnicodeEncodeError 错误:

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)

奇怪的是,这段代码 sn-p 在具有相同 python 版本(3.6.9)的 ubuntu 服务器上工作。 我不明白为什么 json 模块试图编码为 ascii。我认为从 python3 开始,标准是使用 unicode utf-8。

【问题讨论】:

    标签: json python-3.x unicode utf-8


    【解决方案1】:

    不,您的错误与 JSON 或 Python3 编码无关。您的错误与您的控制台字符集有关。您的语言环境具有 ASCII 字符集,因此 python 无法打印您的字符串。

    您应该转换并指定如何处理编码错误,在使用print 时也是如此。

    您可能应该安装/使用支持 UTF-8 的语言环境。

    【讨论】:

    • 你拯救了我的周末!无法猜到 ubuntu 没有附带 utf8。
    • 它带有UTF-8,但默认root编码是C,它只使用ASCII,并且在docker上有时用户不会设置好的语言环境,所以他们仍然是基本的C (适用于服务器)。 en_US.UTF-8 是一个很好的默认值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2014-12-27
    • 2016-01-29
    相关资源
    最近更新 更多