API调用上的UnicodeEncodeError(json) [英] UnicodeEncodeError on API-call (json)
问题描述
我正在尝试打印出此API调用的结果,但出现了UnicodeEncodeError.可能是超级菜鸟的问题,但对此非常感谢:)
I am trying to print out the result of this API-call, but I am getting an UnicodeEncodeError. Probably super noob question, but would really appreciate any help with this :)
import http.client
import json
api_key = 'hidden'
connection = http.client.HTTPConnection('api.football-data.org')
headers = { 'X-Auth-Token': api_key, 'X-Response-Control': 'minified' }
connection.request('GET', '/v1/competitions', None, headers)
response = json.loads(connection.getresponse().read().decode())
print(response)
错误:
回溯(最近通话最近): 在第13行的"/Users/kjetilbergtun/Dropbox/My Python Projects/footballapi.py"文件中 打印(响应)
Traceback (most recent call last): File "/Users/kjetilbergtun/Dropbox/My Python Projects/footballapi.py", line 13, in print(response)
UnicodeEncodeError :"ascii"编解码器无法在位置51编码字符"\ xe9":序数不在范围内(128)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 51: ordinal not in range(128)
推荐答案
encode
将字符串中的Unicode字符转换为可以发送到输出设备的字节流.
encode
is used by print
to convert the Unicode characters in your string to a byte stream that can be sent to your output device.
在启动Python之前,您可以设置环境变量 mbcs
,在其他地方尝试utf-8
,如果您不知道应该怎么做.如果您不提供编码,则默认值为ascii
,它仅适用于最简单的字符串.
Before you start Python, you can set the environment variable PYTHONIOENCODING
to the encoding required by your console. I'd recommend trying mbcs
on Windows and utf-8
everywhere else if you don't know what that should be. If you don't provide an encoding the default will be ascii
, which only works on the simplest strings.
这篇关于API调用上的UnicodeEncodeError(json)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!