0

I wrote a simple program to parse json:

#! /usr/bin/env python

import urllib2
import json

so = 'https://api.stackexchange.com/2.2/users/507256?order=desc&sort=reputation&site=stackoverflow'

j = urllib2.urlopen(so)
print j.read()
j_obj = json.loads(j.read())

It fails with following output:

Traceback (most recent call last):
  File "./so.sh", line 12, in <module>
    j_obj = json.loads(j.read())
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Any idea what I am doing wrong?

1 Answer 1

3

You cannot read the response twice. Remove the print line, or store the result of the j.read() call in a variable.

Next, the Stack Exchange API returns gzipped data, so you'll have to unzip it first:

import zlib

j = urllib2.urlopen(so)
json_data = j.read()
if j.info()['Content-Encoding'] == 'gzip':
    json_data = zlib.decompress(json_data, zlib.MAX_WBITS + 16)

print json_data
j_obj = json.loads(json_data)

You probably want to switch to using the requests module, which handles JSON and content encoding transparently:

import requests

so = 'https://api.stackexchange.com/2.2/users/507256?order=desc&sort=reputation&site=stackoverflow'
response = requests.get(so)
j_obj = response.json()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.