datetime.date(2014, 4, 25) is not JSON serializable in Django

datetime, django, json, python, serialization

Solution

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)

Problem

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.

Original source

Related problems