Parse JSON objects in Python

Overview

In this post we will explain how you can parse JSON objects in Python.
Knowing how to parse JSON objects is useful when you want to access an API
from various web services that gives the response in JSON.

Getting Started

First thing you have to do, is to find an URL to call the API.
In my example, I will use the Twitter API.

Using the Twitter API to parse data

This is a very simple program, just to give you an idea of how it works.

#Importing modules
import json
import urllib2
# Open the URL and the screen name
url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=wordpress"
# This takes a python object and dumps it to a string which is a JSON representation of that object
data = json.load(urllib2.urlopen(url))
#print the result
print data

If you are interested to see another example of how to use JSON in Python, please
have a look at the "IMDB Crawler" script here
To use the Twitter API, see the official documentation on Twitter.
https://dev.twitter.com/docs

Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.