请求返回字节,我无法解码它们

kod*_*tes 19 python byte json decoding python-requests

本质上我向一个网站提出了一个请求并得到了一个字节响应:b'[{"geonameId:"703448"}..........'. 我很困惑,因为虽然它是字节类型,但它是非常人类可读的,看起来像一个json列表.我知道响应是在latin1编码的运行r.encoding中返回的ISO-859-1,我试图解码它,但它只返回一个空字符串.这是我到目前为止所拥有的:

r = response.content
string = r.decode("ISO-8859-1")
print (string)
Run Code Online (Sandbox Code Playgroud)

这是打印空行的地方.但是,当我跑

len(string)
Run Code Online (Sandbox Code Playgroud)

我得到:返回31023 如何在不返回空字符串的情况下解码这些字节?

小智 18

另一种解决方案是使用response.text,它以unicode的形式返回内容

Type:        property
String form: <property object at 0x7f76f8c79db8>
Docstring:  
Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using
``chardet``.

The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
Run Code Online (Sandbox Code Playgroud)

  • 这是一个比接受的答案好得多的想法,因为它将使用适当的编码. (2认同)

mzc*_*mzc 14

你试着用json模块解析它吗?

import json
parsed = json.loads(response.content)
Run Code Online (Sandbox Code Playgroud)

  • 当你做`json.loads(response.content.decode('latin1'))`` (3认同)
  • 是的,我得到了:`JSON对象必须是str,而不是'bytes' (2认同)

Mar*_*oma 9

r.textr.content。第一个是字符串,第二个是字节。

你要

import json

data = json.loads(r.text)
Run Code Online (Sandbox Code Playgroud)