UnicodeEncodeError on API-call (json)

2019-07-13 20:30发布

问题:

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"))