2014-10-05 183 views
0

我寫了一個簡單的程序來解析JSON:蟒蛇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()) 

它失敗,並輸出如下:

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 

任何想法,我做錯了什麼?

回答

3

您無法讀取響應兩次。刪除print行,或將j.read()調用的結果存儲在變量中。

然後,堆棧交易所API返回gzip壓縮的數據,所以你必須先解壓縮它:

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) 

你可能想切換到使用requests module,它處理JSON和內容編碼透明:

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()