检索到的 JSON 是正确的,问题与 URL 检索或 JSON 转换无关。问题是通过终端输出print
。Pre-Python 3.6 将 Unicode 字符串打印到终端会在 Windows 上以终端的编码对输出进行编码,因此UnicodeEncodeError
. 例如,美国 Windows 命令提示符默认为cp437
:
C:\>chcp
Active code page: 437
在 Python 3.6 之前的版本中,如果使用了代码页之外的字符,则将 Unicode 字符串打印到终端会失败。请注意,它正在尝试使用终端的活动代码页:
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'\N{EURO SIGN}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' in position 0: character maps to <undefined>
在 Python 3.6 中,在 Windows 上打印字符使用控制台 Unicode API,并忽略代码页:
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\N{EURO SIGN}')
€
要绕过编码错误,在 Python 3.x 上,您可以print(ascii(resp.json()))
看到响应是正确的。Python 2.x 你可以使用print repr(resp.json())
. 两者都只显示 ASCII 字符,非 ASCII 被打印为转义码。
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print repr(u'\N{EURO SIGN}')
u'\u20ac'