JSON encoding custom objects

suggest change

If we just try the following:

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

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):
		try:
			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()
print(encoder.encode(data))
# prints {"datetime": "2016-09-26T04:44:00"}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents