Explain Codes LogoExplain Codes Logo

Serialising an Enum member to JSON

python
enum
serialization
json
Nikita BarsukovbyNikita Barsukov·Mar 6, 2025
TLDR

Transform an Enum to JSON by implementing a custom encoder that outputs Enum values. Leverage Python's json module, inheriting from JSONEncoder:

import json from enum import Enum # Our very own Enum class Color(Enum): RED = 'red' GREEN = 'green' BLUE = 'blue' class EnumEncoder(json.JSONEncoder): def default(self, obj): # Let me be frank, or rather let me be Enum return obj.value if isinstance(obj, Enum) else super().default(obj) # And...Action! json_str = json.dumps(Color.RED, cls=EnumEncoder)

This snippet generates a JSON string from an Enum member, by transforming the Enum's value into its literal value, ensuring a "no surprises" serialization.

Safeguarding uniqueness with Enums

Keep your Enumerators unique and avoid "seeing double". Apply @unique decorator to your Enums to prevent value collisions.

from enum import Enum, unique @unique class UniqueColor(Enum): RED = 1 GREEN = 2 BLUE = 3

Choosing your serialization flavor

If a string representation is your cup of tea, use json.dumps with default=str. A handy shortcut for Python 3.7+ users:

json_str = json.dumps(UniqueColor.RED, default=str) # "1" is the output, straight and simple

And for those favoring integers, use IntEnum to create a smooth serialization experience:

from enum import IntEnum class Color(IntEnum): RED = 1 GREEN = 2 BLUE = 3 json_str = json.dumps(Color.RED) # Outputs "1", a neat integer

The lambda magic

For a clean inline transformation, embed a lambda function in json.dumps to ensure Enum value representation:

json_str = json.dumps(Color.RED, default=lambda x: x.value if isinstance(x, Enum) else str(x)) # for the minimalist in you

Decoding Enums from JSON

The as_enum function

To switch things back and decode JSON to Enum, create a nifty function, as_enum, for smooth reconversion:

def as_enum(enum_class, value): return enum_class(value) if value in enum_class._value2member_map_ else value color = as_enum(Color, 'RED') # Unmasks itself as Color.RED

Preserving the Enum state

When accuracy is king, pick the appropriate serialization method. How you choose affects the Enum conversion back, be it names or values.