Borislav Hadzhiev
Fri Jun 17 2022·1 min read
Photo by Jeremy Bishop
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.
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
.
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.
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:
Enum
, specify mix-in types before the Enum
class.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
).