3 Jun 2013

Reading http JSON response in Python


Make http request that returns JSON response.               
                   >>fileObj = urllib.urlopen("http://www.omdbapi.com/?t=Fight Club")


Get JSON response from fileObj
                    >>jsonData =  fileObj.read()

 if you print this jsonData , it will look like this.
{
    "Title":"Fight Club",
    "Year":"1999",
    "Rated":"R",
    "Released":"15 Oct 1999",
    "Runtime":"2 h 19 min",
    "Genre":"Drama",
    "Director":"David Fincher",
    "Writer":"Chuck Palahniuk, Jim Uhls",
    "Actors":"Brad Pitt, Edward Norton, Helena Bonham Carter, Meat Loaf",
    "Plot":"An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an         underground fight club that evolves into something much, much more...",
    "Poster":"http://ia.media-imdb.com/images/M/MV5BMjIwNTYzMzE1M15BMl5BanBnXkFtZTcwOTE5Mzg3OA@@._V1_SX300.jpg",
    "imdbRating":"8.9",
    "imdbVotes":"727,988",
    "imdbID":"tt0137523",
    "Type":"movie",
    "Response":"True"
}


Now you have whole JSON response , what if you are only interested in some particular response field(s) ,say 'Director'  ?
Lets see how we can get particular field(s) of JSON response.

Convert json object into python dictionary
                  >>import simplejson
                  >>response_dict = simplejson.loads(jsonData)


Use json data from response_dict to get field
                >>response_dict['Director']
                     David Fincher


So thats how you can read JSON response ,  by the way that was damn good movie....!!.

No comments:

Post a Comment