请求响应中的非“ascii”字符

5 python unicode python-3.x python-requests

我使用 requests 从 API 源获取 json 数据

\n\n
req = requests.get('url')\ncontext = json.loads(req.text)\nprint(context)\n
Run Code Online (Sandbox Code Playgroud)\n\n

返回错误

\n\n
UnicodeEncodeError at /view/\n'ascii' codec can't encode characters in position 26018-26019: ordinal not in range(128)\nUnicode error hint\n\nThe string that could not be encoded/decoded was: OLYUR\xc3\x83\xe2\x80\xb0THANE\n
Run Code Online (Sandbox Code Playgroud)\n\n

我查了一下req.text,没有发现有非ascii字符。出现后json.loads(..)

\n

Man*_*ngh 2

尝试这个:

request_txt = req.text.encode('utf-8')
context = json.loads(request_txt)
Run Code Online (Sandbox Code Playgroud)

您需要应用于.encode('utf-8')引发此错误的字符串。