Load and Parse JSON Data with Hook in Python

I have JSON data from my API, and I need comsume those data.
Python have an awesome built in function json and fully integrated with json data. Here is my format data of my json response.

'[{"date": "12-10-2015", "title": "Python 101"}, 
{"date": "12-07-2012", "title": "Vacation"}, 
{"date": "11-10-2013", "title": "Cooking Master"}, 
{"date": "10-01-2011", "title": "Data Science in Nutshell"}, 
{"date": "17-07-2009", "title": "Sublime Text Review"}]'

The problem is, “date” object in my json is a String and I have to parse it to datetime while I’m parsing the data. And here is it, how to parse json response to python dictionary and parse “date” key to datetime.

import json
from datetime import datetime

json_string = '[{"date": "12-10-2015", "title": "Python 101"}, 
{"date": "12-07-2012", "title": "Vacation"}, 
{"date": "11-10-2013", "title": "Cooking Master"}, 
{"date": "10-01-2011", "title": "Data Science in Nutshell"}, 
{"date": "17-07-2009", "title": "Sublime Text Review"}]'

def parse_date(data):
    if 'date' in data:
        # Convert String date to python datetime object.
        data['date'] = datetime.strptime(data['date'], '%d-%B-%Y')
    return data

# Parse JSON data including parse date string key.
parse_data = json.loads(json_string, object_hook=parse_date)

Referece: https://docs.python.org/2/library/json.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s