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.
I’ve prepared a quick demo below. Once I figured it out I laughed at myself for not seeing it earlier.
Let’s test it out in our interpreter
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.