- Encoding Python Enum to JSON
- Convert Enum to JSON in Python
- Introduction:
- Method 1: Using a dictionary and the JSON module
- Output:
- Method 2: Using a custom encoder and the JSON module
- Output:
- Method 3: Using a custom encoder function and the JSON module
- Output:
- Conclusion:
- Related Post
- Python enum to json
- # Table of Contents
- # Convert an Enum to a String in Python
- # Implementing the __str__ method in the Enum class
- # Using square bracket notation to access Enum members
- # Convert a String to an Enum in Python
Encoding Python Enum to JSON
It is an old question. But no one gave this very simple answer.
You just need to subclass your Enum from str.
import json from enum import Enum class TestEnum(str, Enum): one = "first" two = "second" three = "third" test = print(json.dumps(test))
You can’t use anything but strings as keys in dictionaries you want to convert to JSON. The encoder doesn’t give you any other options; the default hook is only called for values of unknown type, never for keys.
Convert your keys to strings up front:
def convert_keys(obj, convert=str): if isinstance(obj, list): return [convert_keys(i, convert) for i in obj] if not isinstance(obj, dict): return obj return json.dumps(convert_keys(test))
This recursively handles your dictionary keys. Note that I included a hook; you can then choose how to convert enumeration values to strings:
def enum_names(key): if isinstance(key, TestEnum): return key.name return str(key) json.dumps(convert_keys(test, enum_names))
You can use the same function to reverse the process when loading from JSON:
def names_to_enum(key): try: return TestEnumPython enum to json except KeyError: return key convert_keys(json.loads(json_data), names_to_enum)
>>> def enum_names(key): . if isinstance(key, TestEnum): . return key.name . return str(key) . >>> json_data = json.dumps(convert_keys(test, enum_names)) >>> json_data '' >>> def names_to_enum(key): . try: . return TestEnumPython enum to json . except KeyError: . return key . >>> convert_keys(json.loads(json_data), names_to_enum) : 'This', : 'should', : 'work!'>
Convert Enum to JSON in Python
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 = # Convert dictionary to JSON string json_string = json.dumps(color_dict) print(json_string)
Output:
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:
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 '' is not JSON serializable") # Convert Enum to JSON string json_string = json.dumps(Color, default=enum_encoder) print(json_string)
Output:
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.
Related Post
Python enum to json
Last updated: Feb 18, 2023
Reading time · 8 min
# Table of Contents
# Convert an Enum to a String in Python
To convert an enum to a string in Python:
- Access the name of the enum, e.g. Color.RED.name .
- Access the value of the enum, e.g. Color.RED.value .
- Optionally, use the str() class to convert the value to a string.
Copied!from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' # 👇️ human readable string representation print(Color.RED) # 👉️ Color.RED # 👇️ repr() shows the value as well print(repr(Color.RED)) # 👉️ # 👇️ get name of enum print(Color.RED.name) # 👉️ RED # 👇️ get value of enum print(Color.RED.value) # 👉️ stop # 👇️ if enum value is int, you can convert it to str print(str(Color.RED.value)) # 👉️ stop
If the value is not a string and you need to convert it to one, pass it to the str() class.
Copied!from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' # 👇️ if enum value is int, you can convert it to str print(str(Color.RED.value)) # 👉️ stop
The str() class returns the string representation of the supplied value.
# Implementing the __str__ method in the Enum class
Alternatively, you can implement the __str__() method in the class.
Copied!from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' def __str__(self): return str(self.value) print(Color.RED) # 👉️ "stop"
The _ _ str _ _ () method is called by str(object) and the built-in functions format() and print() and returns the informal string representation of the object.
Now you can get the value of the enum directly, without accessing the value attribute on the enum member.
# Using square bracket notation to access Enum members
You can also use square brackets to access enum members.
Copied!from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' name = 'RED' print(Color[name].value) # 👉️ 'stop' print(Color['RED'].value) # 👉️ 'stop'
This is useful when you don’t know the name of the enum member ahead of time (because it’s read from a file or fetched from an API).
You can use a simple for loop if you need to iterate over an enum.
Copied!from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' for color in Color: print(color) print(color.name, color.value)
You can use a list comprehension to check if a specific value is in an enum.
Copied!from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' # 👇️ check enum member type print(type(Color.RED)) # 👉️ # 👇️ check if member belongs to Enum print(isinstance(Color.RED, Color)) # 👉️ True values = [member.value for member in Color] print(values) # 👉️ ['stop', 'go', 'get ready'] if 'stop' in values: # 👇️ this runs print('stop is in values')
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
# Convert a String to an Enum in Python
To convert a string to an enum in Python:
- Import the Enum class from the enum module.
- Declare an enum by extending the Enum class.
- Assign class properties on the enum class.
Copied!from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' # 👇️ human-readable string representation print(Sizes.MEDIUM) # 👉️ Sizes.MEDIUM # 👇️ repr() shows the value as well print(repr(Sizes.MEDIUM)) # 👉️ # 👇️ get the name of the enum print(Sizes.MEDIUM.name) # 👉️ MEDIUM # 👇️ get the value of the enum print(Sizes.MEDIUM.value) # 👉️ md # 👇️ if the enum value is int, you can convert it to str print(str(Sizes.MEDIUM.value)) # 👉️ md # 👇️ access enum member using a string print(Sizes['LARGE'].value) # 👉️ lg
Enums are created using the class syntax and enum members (e.g. Sizes.SMALL ) can be anything: int , str , etc.
The example creates an enumeration with 3 members that all have values of type string.