API 调用上的 UnicodeEncodeError (json) [英] UnicodeEncodeError on API-call (json)

查看:22
本文介绍了API 调用上的 UnicodeEncodeError (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)

错误:

回溯(最近一次调用最后一次):文件/Users/kjetilbergtun/Dropbox/My Python Projects/footballapi.py",第 13 行,在打印(响应)

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 用于 print 将字符串中的 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 之前,您可以设置环境变量 PYTHONIOENCODING 到您的控制台所需的编码.如果您不知道应该是什么,我建议在 Windows 上尝试 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆