Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialising an Enum member to JSON

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?

like image 872
Bilal Syed Hussain Avatar asked Jun 30 '14 01:06

Bilal Syed Hussain


People also ask

Can we pass enum in JSON?

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 .

How do you serialize an enum?

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.

Can you serialize an enum C#?

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.


1 Answers

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.

like image 98
Justin Carter Avatar answered Oct 11 '22 05:10

Justin Carter