Oct. 06, 2012

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. 
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 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:
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.