Why json serialization of datetime objects in python doesn't work out of the box for datetime objects

Why json serialization does not work for datetime objects. Since I understand json serialization, the basic idea for any object can be called by the __str__ built-in function, and then the urlencode object you get as the answer. But in case of datetime, I get the following error:

 TypeError: datetime.datetime(2012, 5, 23, 18, 38, 23, 37566) is not JSON serializable 

while there is __str__ ie a way to create an object that is already available, but it seems like a conscious decision not to do this, why not?

+50
json python serialization simplejson
May 23 '12 at 13:52
source share
4 answers

No, this does not work in the json module. The module provides you with the default encoder: json.JSONEncoder . You must extend this to provide an implementation of the default method for serializing objects. Something like that:

 import json import datetime from time import mktime class MyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return int(mktime(obj.timetuple())) return json.JSONEncoder.default(self, obj) print json.dumps(obj, cls=MyEncoder) 

As others have correctly pointed out, the reason is that the standard for json does not indicate how the date can be represented.

+88
May 23 '12 at 14:01
source share

How would you like them to be serialized?

JSON does not indicate how to handle dates, so the python json library cannot decide on how to present them for you then. It completely depends on how the other side (browser, script, independently) handles dates in JSON.

+10
May 23 '12 at 1:57 pm
source share

An easy way to fix the json module so that serialization supports date and time.

 import json import datetime json.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None) 

Instead of using json serialization, as you always do, this time with a datetime that serializes as isoformat.

 json.dumps({'created':datetime.datetime.now()}) 

Result: '{"created": "2015-08-26T14: 21: 31.853855"}'

See more details and some warnings: stack overflow

+8
Aug 26 '15 at 11:31 on
source share

If you want to get encoding and decoding data without doing it, you can use json_tricks , which is a wrapper that adds encoding and decoding for various popular types. Just install:

 pip install json_tricks 

and then import from json_tricks instead of json , for example:

 from json_tricks import dumps, loads json = dumps({'name': 'MyName', 'birthday': datetime.datetime(1992, 5, 23, 18, 38, 23, 37566)}) me = loads(json) 

Disclaimer: This is done by me. Because I had the same problem.




If you want to automatically serialize anything that can be compressed, you can do this with the standard implementation very easily:

 dumps(obj, default=str) 

But note that this has disadvantages, for example. none of them will be deserialized without extra effort, and maybe sometimes you just don’t want to serialize anything (for example, a large numpy array function), but instead get a warning that will be disabled by this method.

+2
Oct 19 '16 at 21:51
source share



All Articles