python - 尝试在 python 中解码 HTTP 响应。无法弄清楚JSON解码

标签 python json encoding utf-8 gzip

这是基本请求:

req = urllib2.Request(f"https://www.voter.ie/api/search/name/{name}/surname/{surname}/eircode/{eircode}/lang/en")

req.add_header("Connection", "keep-alive")
req.add_header("Accept", "application/json, text/plain, */*")
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 OPR/62.0.3331.99")
req.add_header("Accept-Encoding", "gzip, deflate, br")
req.add_header("Accept-Language", "en-US,en;q=0.9")

response = urllib2.urlopen(req)

这是 header ,我可以看到它是 Content-Type 中的 JSON,编码是 utf-8:

response.getheaders()

[('Transfer-Encoding', 'chunked'),
 ('Content-Type', 'application/json; charset=utf-8'),
 ('Content-Encoding', 'gzip'),
 ('Vary', 'Accept-Encoding'),
 ('Server', 'Kestrel'),
 ('Request-Context', 'appId=cid-v1:25017a8d-4490-471a-a8d0-e9e17860f987'),
 ('Strict-Transport-Security', 'max-age=2592000'),
 ('X-Content-Type-Options', 'nosniff'),
 ('Referrer-Policy', 'no-referrer'),
 ('X-XSS-Protection', '1; mode=block'),
 ('X-Frame-Options', 'Deny'),
 ('X-Powered-By', 'ASP.NET'),
 ('Date', 'Fri, 02 Aug 2019 14:45:33 GMT'),
 ('Connection', 'close')]

因此,当我尝试读取或解码它时,我遇到了很多错误,但首先它看起来是这样的。我没有发布完整的字符串,因为它太长了,但这是一个示例:

response.read()

b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07`\x1cI\x96%&/m\xca{\x7fJ\xf5J\xd7\xe0t\xa1\x08\x80`\x13$\xd8\x90@\x10\xec\xc1\x88\xcd\xe6\x92\xec\x1diG#)\xab*\x81\xcaeVe]f\x16@\xcc\xed\x9d\xbc\xf7\xde{\xef\xbd\xf7\xde{\xef\xbd\xf7\xba;\x9dN\'\xf7\xdf\xff?\\fd\x01l\xf6\xceJ\xda\xc9\x9e!\x80\xa

我尝试使用我在 StackOverflow 上找到的方法:

response.read().decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte


raw_data = response.read()
json.loads(raw_data.decode('utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte


string = response.read().decode('utf-8')
json_obj = json.loads(string)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

我做错了什么?

最佳答案

正如响应 header 所暗示的,数据已使用 gzip 压缩。在执行任何其他操作之前,您需要解压缩它。

import gzip, json
gz = response.read()
j = gzip.decompress(gz)
data = json.loads(j.decode('utf-8')) 

关于python - 尝试在 python 中解码 HTTP 响应。无法弄清楚JSON解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57328953/

相关文章:

java - 使用 Jackson 序列化类时添加类型信息,以便可以使用接口(interface)类型反序列化而不使用注释?

java - 如何将 List<ViewHolder> 转换为 JSON 并通过 POST 请求发送到服务器

python - 如何在 PyCharm 中使用 Anaconda 基础环境

python - 将词嵌入添加到 word2vec gensim 模型

python - 两个子图上的两个颜色条,相同的图形

ruby-on-rails - Rails 3 + 设计 - 如何让设计以 JSON 响应

python - python中的random.choice([x, y, z]),为什么种子没有改变?

java - 如何让 SAX 解析器从 xml 声明中确定编码?

encryption - 使用 OpenSSL 验证 PKCS#11 生成的 DSA 签名

.net - 如何在不丢失奇数字符的情况下读取文本文件?