python json parsing error -
python json parsing error -
i wrote simple programme parse json:
#! /usr/bin/env python import urllib2 import json = '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 next output:
traceback (most recent phone 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 homecoming _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 decoded") valueerror: no json object decoded
any thought doing wrong?
you cannot read response twice. remove print
line, or store result of j.read()
phone call in variable.
next, stack exchange api returns gzipped data, you'll have unzip 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 want switch using requests
module, handles json , content encoding transparently:
import requests = 'https://api.stackexchange.com/2.2/users/507256?order=desc&sort=reputation&site=stackoverflow' response = requests.get(so) j_obj = response.json()
python json
Comments
Post a Comment