Image for post
Image for post

Convert a Python Enum to JSON

Alexander Hultnér
Mar 12, 2018 · 1 min read

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.

Hultnér

Product Development in the connected world

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store