UnicodeEncodeError on API-call (json)

浪子不回头ぞ 提交于 2019-12-10 23:29:11

问题


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)

Error:

Traceback (most recent call last): File "/Users/kjetilbergtun/Dropbox/My Python Projects/footballapi.py", line 13, in print(response)

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 51: ordinal not in range(128)


回答1:


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.

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.




回答2:


The problem is you are trying to process a non-ascii character. You need to encode it in unicode with .encode('utf-8')




回答3:


Since your response is a bytes object, you need to decode to get back the string

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)
print (connection.getresponse().read().decode("utf-8"))


来源:https://stackoverflow.com/questions/45154063/unicodeencodeerror-on-api-call-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!