How do I serialise a Python Enum
member to JSON, so that I can deserialise the resulting JSON back into a Python object?
For example, this code:
from enum import Enum import json class Status(Enum): success = 0 json.dumps(Status.success)
results in the error:
TypeError: <Status.success: 0> is not JSON serializable
How can I avoid that?
All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .
To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.
In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what those numbers actually mean.
I know this is old but I feel this will help people. I just went through this exact problem and discovered if you're using string enums, declaring your enums as a subclass of str
works well for almost all situations:
import json from enum import Enum class LogLevel(str, Enum): DEBUG = 'DEBUG' INFO = 'INFO' print(LogLevel.DEBUG) print(json.dumps(LogLevel.DEBUG)) print(json.loads('"DEBUG"')) print(LogLevel('DEBUG'))
Will output:
LogLevel.DEBUG "DEBUG" DEBUG LogLevel.DEBUG
As you can see, loading the JSON outputs the string DEBUG
but it is easily castable back into a LogLevel object. A good option if you don't want to create a custom JSONEncoder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With