How it works...

To generate JSON representation of Python objects, the json.dumps method is used. This method accepts an additional argument, cls, where a custom encoder class can be provided:

json.dumps({'key': 'value', cls=CustomJSONEncoder)

The default method of the provided class will be called whenever it is required to encode an object that the encoder doesn't know how to encode.

Our CustomJSONEncoder class provides a default method that handles encoding dates, times, generators, decimals, and any custom class that provides a __json__ method:

class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): if hasattr(obj, '__json__') and callable(obj.__json__): return obj.__json__() elif isinstance(obj, (datetime.datetime, datetime.time)): ...

Get Modern Python Standard Library Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.