How to Serialize Python Enums to JSON
This guide shows the simplest and most direct way to serialize a Python Enum to JSON.
Using str or int as Base Class
If the values in your enum are strings or integers, you can inherit from str or int:
from enum import Enum
import json
class Color(str, Enum): # Inherit from str, then Enum
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
my_json = json.dumps(Color.RED)
print(my_json) # Output: "stop"
class Color(int, Enum):
RED = 1
GREEN = 2
YELLOW = 3
my_json = json.dumps(Color.RED)
print(my_json) # Output: 1
- The
strclass should come before theEnumclass. - If the values are of type string, extend from
strclass. - If the values are of type integer, extend from
intclass.