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.
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
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
Recommended Python Training – DataCamp
For Python training, our top recommendation is DataCamp.
Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.
Datacamp has beginner to advanced Python training that programmers of all levels benefit from.
Read more about: