Python Language JSON Module JSON encoding custom objects

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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"}

Got any Python Language Question?