Contributors: 1 Tuesday, July 26, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap

JSON encoding custom objects


If we just try the following:

import json
from datetime import datetime
data = {'datetime': datetime(2016, 9, 26, 4, 44, 0)}

we get an error saying TypeError: datetime.datetime(2016, 9, 26, 4, 44) is not JSON serializable.

To be able to serialize the datetime object properly, we need to write custom code for how to convert it:

class DatetimeJSONEncoder(json.JSONEncoder):
    def default(self, obj):
            return obj.isoformat()
        except AttributeError:
            # obj has no isoformat method; let the builtin JSON encoder handle it
            return super(DatetimeJSONEncoder, self).default(obj)

and then use this encoder class instead of json.dumps:

encoder = DatetimeJSONEncoder()
# prints {"datetime": "2016-09-26T04:44:00"}