我用python3查询Github的Jobs API,使用requests
库,但遇到了解析响应的错误。
图书馆:http://docs.python-requests.org/en/latest/
码:
import requests
import json
url = 'https://jobs.github.com/positions.json?'
response = requests.get(url)
print(response.json())
错误:
UnicodeEncodeError:'ascii'编解码器无法编码位置321的字符'\ u2019':序号不在范围内(128)
过去在Ruby中使用这个API,我从来没有遇到过这个问题。
我也尝试将它转换为字典,但它导致了同样的错误。
还有其他关于UnicodeEncodeError
的问题(主要是re:打开文件),但我不熟悉Python并且没有发现它们有用。
首先,检查响应是否实际为JSON。尝试打印response.text
,看看它是否看起来像一个有效的JSON对象。
假设它是JSON:它非常“hack”-ey,但是你可以用它们的转义Unicode表示替换非ASCII字符:
def escape_unicode(c):
return c.encode('ascii', 'backslashreplace').decode('ascii')
response = ...
text = response.text
escaped = re.sub(r'[^\x00-\x7F]', lambda m: escape_unicode(m.group(0)), text)
json_response = json.loads(escaped)