Convert a Python Enum to JSON

A trivial way to make a Python Enum which is based on string tokens JSON-serializable is to inherit both str and Enum. Look at the example below for some pointers.

How?

I’ve prepared a quick demo below. Once I figured it out I laughed at myself for not seeing it earlier.

Hey, did I leave out your pet? Well this isn’t production code.

Let’s test it out in our interpreter

It’s reall that easy!

No need for a custom JSONEncoder, str is already serializable. The built in IntEnum works the same way, in fact that’s how I figured it out.

Taking it further

This applies for other classes as well. E.g. let a class inherit dict to gain it’s properties; including JSON serialization with the default encoder.


Originally published at hultner.github.io on March 12, 2018.