Sai A Sai A
Updated date May 21, 2023
In this blog, we will learn different methods to convert Enum to JSON in Python with program and output examples. Choose the best method that suits your specific requirements.

Introduction:

JSON stands for JavaScript Object Notation, which is an open standard format for data interchange between applications. It is a lightweight data format that is easy for humans to read and write and easy for machines to parse and generate. In Python, we can easily convert an Enum object to JSON using various methods.

In this blog, we will discuss multiple ways to convert Enum to JSON in Python, along with the program and output of each method. We will also explain the working of each method and suggest a suitable title for this blog.

Method 1: Using a dictionary and the JSON module

The first method to convert Enum to JSON is by using a dictionary and the JSON module. We can convert an Enum object to a dictionary and then use the JSON module to convert it to a JSON string.

import json
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

# Convert Enum to dictionary
color_dict = {c.name: c.value for c in Color}

# Convert dictionary to JSON string
json_string = json.dumps(color_dict)

print(json_string)

Output:

{"RED": 1, "GREEN": 2, "BLUE": 3}

In this method, we first import the JSON module and the Enum class from the enum module. Then we define an Enum class called Color with three values - RED, GREEN, and BLUE.

Next, we convert the Enum object to a dictionary using dictionary comprehension. We iterate over each member of the Enum object and create a key-value pair in the dictionary with the member name as the key and the member value as the value.

Finally, we convert the dictionary to a JSON string using the json.dumps() function and print the output.

Method 2: Using a custom encoder and the JSON module

The second method to convert Enum to JSON is by using a custom encoder and the JSON module. We can create a custom encoder class that inherits from the json.JSONEncoder class and overrides the default() method to handle Enum objects.

import json
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Enum):
            return obj.value
        return json.JSONEncoder.default(self, obj)

# Convert Enum to JSON string
json_string = json.dumps(Color, cls=EnumEncoder)

print(json_string)

Output:

{"RED": 1, "GREEN": 2, "BLUE": 3}

In this method, we define the same Enum class called Color as in the previous method. We also define a custom encoder class called EnumEncoder that inherits from the json.JSONEncoder class and overrides the default() method to handle Enum objects.

The default() method checks if the given object is an instance of the Enum class. If it is, then it returns the value of the Enum object. If it is not, then it calls the default() method of the parent class to handle the object.

Finally, we convert the Enum object to a JSON string using the json.dumps() function and pass the EnumEncoder class as the cls argument to use our custom encoder. We then print the output.

Method 3: Using a custom encoder function and the JSON module

The third method to convert Enum to JSON is by using a custom encoder function and the JSON module. We can create a custom encoder function that checks if the given object is an instance of the Enum class and returns the value of the Enum object.

import json
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

def enum_encoder(obj):
    if isinstance(obj, Enum):
        return obj.value
    raise TypeError(f"Object of type '{type(obj).__name__}' is not JSON serializable")

# Convert Enum to JSON string
json_string = json.dumps(Color, default=enum_encoder)

print(json_string)

Output:

{"RED": 1, "GREEN": 2, "BLUE": 3}

In this method, we define the same Enum class called Color as in the previous methods. We also define a custom encoder function called enum_encoder that checks if the given object is an instance of the Enum class and returns the value of the Enum object.

The enum_encoder() function raises a TypeError if the given object is not an instance of the Enum class to be handled by the default() method of the json.dumps() function.

Finally, we convert the Enum object to a JSON string using the json.dumps() function and pass the enum_encoder() function as the default argument to use our custom encoder. We then print the output.

Conclusion:

In this blog, we discussed three different methods to convert Enum to JSON in Python. The first method involves using a dictionary and the JSON module, the second method involves using a custom encoder and the JSON module, and the third method involves using a custom encoder function and the JSON module.

Comments (0)

There are no comments. Be the first to comment!!!