正在尝试用python解码HTTP响应。Can';我搞不懂JSON解码

正在尝试用python解码HTTP响应。Can';我搞不懂JSON解码,python,json,encoding,utf-8,gzip,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-

以下是基本要求:

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)
这里是标题,我可以看到它在
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

我做错了什么

响应头提示,数据已经用gzip压缩。你需要先解压,然后再做其他事情

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

这就解决了问题。非常感谢你。以前从未遇到过压缩响应。现在我知道了。收到一个错误AttributeError:“module”对象没有属性“decompress”@Patlatus
gzip。decompress
是在Python3.2中添加的,因此如果您使用的是早期的Python,则需要使用该版本中可用的工具(恐怕我现在没有时间调查)。