EDIT
This question is not a duplicate of How to overcome "datetime.datetime not JSON serializable"? Because, although this is the same problem, it provides a specific context: Django. And so, there are some solutions that apply here and that do not apply on the provided link's question.
ORIGINAL QUESTION
I followed How to overcome "datetime.datetime not JSON serializable"? but this is not helping
I tried this code
>>> import datetime >>> a =datetime.date(2014, 4, 25) >>> from bson import json_util >>> b = json.dumps(a,default = json_util.default) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/home/.../python2.7/site-packages/bson/json_util.py", line 256, in default raise TypeError("%r is not JSON serializable" % obj) TypeError: datetime.date(2014, 4, 25) is not JSON serializable
Can somebody help me with a datetime.date
serializer and deserializer.
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. Here is an example of how the error occurs.
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.
The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.
You can also do this:
def date_handler(obj): return obj.isoformat() if hasattr(obj, 'isoformat') else obj print json.dumps(data, default=date_handler)
From here.
Update as per J.F.Sebastian comment
def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() else: raise TypeError print json.dumps(data, default=date_handler)
Convert date to equivalent iso format,
In [29]: datetime.datetime.now().isoformat() Out[29]: '2020-03-06T12:18:54.114600'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With