Python urllib2: Receive JSON response from url

Deepak B picture Deepak B · Dec 17, 2012 · Viewed 160.9k times · Source

I am trying to GET a URL using Python and the response is JSON. However, when I run

import urllib2
response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
html=response.read()
print html

The html is of type str and I am expecting a JSON. Is there any way I can capture the response as JSON or a python dictionary instead of a str.

Answer

Martijn Pieters picture Martijn Pieters · Dec 17, 2012

If the URL is returning valid JSON-encoded data, use the json library to decode that:

import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)   
print data