How to convert an Enum to JSON in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Convert an Enum to JSON in Python #

To convert an enum to JSON, extend from the str or int classes when declaring your enumeration class, e.g. class Color(str, Enum):. You will then be able to serialize the enum members to json directly by using the json.dumps() method.

main.py
from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'

The Color class is a subclass of both str() and Enum.

You can use the int class to create an enum with constants that are also subclasses of int.

main.py
from enum import Enum import json class Color(int, Enum): RED = 1 GREEN = 2 YELLOW = 3 my_json = json.dumps(Color.RED) print(my_json) # 👉️ "1" my_int = json.loads(my_json) print(my_int) # 👉️ 1

This is very similar to using the IntEnum class from the enum module.

main.py
from enum import IntEnum import json class Color(IntEnum): RED = 1 GREEN = 2 YELLOW = 3 my_json = json.dumps(Color.RED) print(my_json) # 👉️ "1" my_int = json.loads(my_json) print(my_int) # 👉️ 1

Instead of extending from int and Enum, we extended from the IntEnum class to achieve the same result.

Note that there are some rules when working with derived enumerations:

  1. When subclassing Enum, specify mix-in types before the Enum class.
  2. While Enum can have members of any type, once additional types are mixed, all the members in the enum must have values of the specified type (e.g. int).
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.