解析JSON url时的Python unicodeDecodeError

时间:2017-04-06 05:56:57

标签: python python-3.x stackexchange-api

我正在使用python 3.4并试图从URL中解析看似有效的JSON输出。例如: http://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow

这是我的代码看起来像

import json
from urllib.request import urlopen


def jsonify(url):
    response = urlopen(url).read().decode('utf8')
    repo = json.loads(response)
    return repo 


 url = jsonify('http://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow');

但是,我收到UnicodeDecodeError utf-8 codec can't decode byte 0x8b in position 1; invalid start byte

等错误

该脚本适用于任何其他API,例如github和许多其他API,但不适用于stackexchange api

1 个答案:

答案 0 :(得分:2)

使用gzip压缩响应,您必须将其解压缩。

$ curl -v http://api.stackexchange.com/2.2/questions\?order\=desc\&sort\=activity\&site\=stackoverflow
*   Trying 198.252.206.16...
* TCP_NODELAY set
* Connected to api.stackexchange.com (198.252.206.16) port 80 (#0)
> GET /2.2/questions?order=desc&sort=activity&site=stackoverflow HTTP/1.1
> Host: api.stackexchange.com
> User-Agent: curl/7.51.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Cache-Control: private
< Content-Type: application/json; charset=utf-8
< Content-Encoding: gzip

有关详细信息,请参阅api.stackexchange docs

减压示例:

import gzip

def jsonify(url):
    response = urlopen(url).read()
    tmp = gzip.decompress(response).decode('utf-8')
    repo = json.loads(tmp)
    return repo