user7342807
user7342807

Reputation: 313

Python unicodeDecodeError on parsing a JSON url

I am using python 3.4 and trying to parse what seems like valid JSON output from a url. ex: http://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow

This is what my code looks like

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');

However, I get errors such as UnicodeDecodeError utf-8 codec can't decode byte 0x8b in position 1; invalid start byte

The script works with any other API, like github and so many others, but not with the stackexchange api

Upvotes: 0

Views: 524

Answers (1)

xrisk
xrisk

Reputation: 3898

The response is compressed using gzip, you have to decompress it.

$ 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

See the api.stackexchange docs for more details.

Example of decompression:

import gzip

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

Upvotes: 2

Related Questions