Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize the datetime in a json object in python?

My original dictionary is

A = {                                                                                                  
    'date': datetime.date(2013, 1, 1),
    'price': 100
}

Since datetime.date is not serializable, I add a default function to deal with that:

B = json.dumps(A, default=lambda obj:obj.isoformat() if hasattr(obj, 'isoformat') else obj)

My question is, how can I deserialize the 'date' field while I use json.loads to convert it back to the original dictionary?

like image 749
waitingkuo Avatar asked Feb 21 '13 06:02

waitingkuo


2 Answers

from datetime import datetime

def load_with_datetime(pairs, format='%Y-%m-%d'):
    """Load with dates"""
    d = {}
    for k, v in pairs:
        if isinstance(v, basestring):
            try:
                d[k] = datetime.strptime(v, format).date()
            except ValueError:
                d[k] = v
        else:
            d[k] = v             
    return d

dump = json.dumps(A, default = f)
json.loads(dump, object_pairs_hook=load_with_datetime)

# {u'date': datetime.date(2013, 1, 1), u'price': 100}
like image 164
root Avatar answered Nov 13 '22 22:11

root


continue to your example code,

C = json.loads(B)
C['date'] = datetime.datetime.strptime(C['date'], '%Y-%m-%d')
print C
# {u'date': datetime.datetime(2013, 1, 1, 0, 0), u'price': 100}
like image 24
Chunliang Lyu Avatar answered Nov 13 '22 22:11

Chunliang Lyu