Why does the JSON serialization not work for datetime objects? As I understand JSON serialization, the basic idea for any object can be called the __str__
built-in function and then URL encode the object that you get as a response. 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 a __str__
, i.e., a way of stringifying the object already available , But it seems like a conscious decision to not do it , why would that be the case?
No, it doesn't work that way in the
json
module. The module provides you with a default encoder:json.JSONEncoder
. You need to extend this to provide your implementation ofdefault
method to serialize objects. Something like this:As others correctly pointed out, the reason is that the standard for JSON does not specify how date time can be represented.