Serialising an Enum member to JSON
Transform an Enum to JSON by implementing a custom encoder that outputs Enum values. Leverage Python's json module, inheriting from JSONEncoder:
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.
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:
And for those favoring integers, use IntEnum to create a smooth serialization experience:
The lambda magic
For a clean inline transformation, embed a lambda function in json.dumps to ensure Enum value representation:
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:
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.
Was this article helpful?