8

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?

3 Answers 3

11
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}
Sign up to request clarification or add additional context in comments.

2 Comments

as a personal preference, i check for a regex instead of the try/except block. but i have object_pairs_hooks that handle multiple formats and require that.
@JonathanVanasco -- Yup, if you have multiple formats, then using a regex could be an alternative, also I would look at the dateutil parser...
3

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}

2 Comments

Is it possible to convert it when doing the json.loads command? I have not only one date information. Thanks!
you may refer to @root's answer, or a more complete solution here
0

Use pickle module

    import pickle
    fileop = open("timeformat.txt","wb")
    pickle.dump(A,fileop)
    fileop.close()
    print pickle.load(open("timeformat.txt","rb"))
    print A['Date']


    >>>{'date': datetime.date(2013, 1, 1), 'price': 100}
    >>>2013-01-01

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.