2014-09-22 93 views
0

urllib2的迴應,我有以下代碼:如何獲得JSON

import urllib2 
response = urllib2.urlopen('http://python.org/') 

什麼是最直接的方式json得到這個?

回答

3

http://python.org/」的輸出未返回json文檔。

您可以檢查類型的輸出如下的:

>>> import urllib2 
>>> response = urllib2.urlopen('http://python.org/') 
>>> response.headers.type 
'text/html' 
>>> 

OK,讓我們看看JSON響應API的一個例子:

>>> response = urllib2.urlopen('http://api.icndb.com/jokes/random') 
>>> response.headers.type 
'application/json' 
>>> 

所以,在這裏的頭型,你可以看到'application/json'這意味着該響應包含json文檔。

>>> import json 
>>> json_docs = json.load(response) 
>>> print json_docs 
{u'type': u'success', u'value': {u'joke': u'How many Chuck Norris require to screw a light  bulb? None, he will screw it all.', u'id': 562, u'categories': []}} 
>>> 
1

給定一個響應對象,你會做

jsondata = json.load(response) 

當然,你將獲取從實際上是JSON數據的URL數據(http://python.org/不是JSON)。