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 give 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.
Start with importing the modules that we need for the program.
import json import urllib2
Open the URL and the screen name.
url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=wordpress"
Print out the result
print data
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.
To use the Twitter API, see the official documentation on Twitter.
https://dev.twitter.com/docs