Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does json serialization of datetime objects in python not work out of the box for datetime objects

Why does the json serialization not work for datetime objects . As I understand json serialization the basic idea for any object can be call the __str__ builtin function and then urlencode 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?

like image 674
dusual Avatar asked May 23 '12 13:05

dusual


People also ask

How do I fix the object of type datetime is not JSON serializable?

The Python "TypeError: Object of type datetime is not JSON serializable" occurs when we try to convert a datetime object to a JSON string. To solve the error, set the default keyword argument to str in your call to the json. dumps() method.

How do you serialize a Date object in Python?

Serialize datetime by converting it into String You can convert dateTime value into its String representation and encode it directly, here you don't need to write any encoder. We need to set the default parameter of a json. dump() or json. dumps() to str like this json.

What is the difference between JSON and serialization?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

How to serialize a DateTime object as JSON using Python?

How to serialize a datetime object as JSON using Python? It is easy to serialize a Python data structure as JSON, we just need to call the json.dumps method, but if our data stucture contains a datetime object we'll get an exception: How can we fix this?

What is serialization in Python?

Serialization is the process of encoding the from naive datat type to JSON format. The Python module json converts a Python dictionary object into JSON object, and list and tuple are converted into JSON array, and int and float converted as JSON number, None converted as JSON null. Attention geek!

How do I call JSON dumps with a DateTime object?

The first call to json.dumps works properly, but once we add a key with a value that is a datetime object, the call throws an exception. The solution is quite simple. The json.dumps method can accept an optional parameter called default which is expected to be a function.

How to convert datetime value to string in JSON?

You can convert dateTime value into its String representation and encode it directly, here you don’t need to write any encoder. We need to set the default parameter of a json.dump () or json.dumps () to str like this json.dumps (obj, default=str).


1 Answers

No it doesn't work that way in json module. The module provides you with a default encoder: json.JSONEncoder. You need to extend this to provide your implementation of default method to serialize objects. Something like this:

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 correctly pointed out, the reason is that the standard for json does not specify how date time can be represented.

like image 134
Vikas Avatar answered Oct 11 '22 08:10

Vikas