David542
David542

Reputation: 110093

How to get urllib2 response in json

I have the following code:

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

What would be the most straightforward way to get this in json ?

Upvotes: 0

Views: 336

Answers (2)

James Sapam
James Sapam

Reputation: 16930

The output of "http://python.org/" is not returning json documents.

You can check the types of your output as below:

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

OK, lets see one example of json response api:

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

So, here in the header type you can see the 'application/json' which means that the reponse contain json documents.

>>> 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': []}}
>>> 

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 992707

Given a response object, you would do

jsondata = json.load(response)

Of course, you will be fetching data from a URL that is actually JSON data (http://python.org/ is not JSON).

Upvotes: 1

Related Questions