JSON serialize Python Enum object

Viewed 976

While serializing Enum object to JSON using json.dumps(...), python will throw following error:

>>> class E(enum.Enum):
...     A=0
...     B=1
>>> import json
>>> json.dumps(E.A)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\guptaaman\Miniconda3\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\guptaaman\Miniconda3\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\guptaaman\Miniconda3\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\guptaaman\Miniconda3\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type E is not JSON serializable

How to make Enum object JSON serializable?

2 Answers

Use enum.IntEnum instead of enum.Enum and it will be serialized as an integer automatically.

Related