typeerror: object of type set is not json serializable

Have you ever encountered the “typeerror object of type set is not json serializable” error message while running on a Python project?

In this article, we will discuss what this error message means and guide you on how to solve it.

Before we go on to the solutions on how to solve the error, we will know first what does JSON Serialization mean.

What is JSON Serialization?

JSON serialization is the process of converting Python objects into a JSON format.

JSON (JavaScript Object Notation) is widely used for data exchange between web applications and web services.

Why you getting this error?

The “TypeError: Object of type set is not JSON serializable” error message occurs because you are trying to serialize a set object using the json.dump() or json.dumps() method.

This error message shows that the JSON module cannot serialize a set object into a JSON format.

Causes of the object of type set is not json serializable error

There are multiple reasons why you may encounter the error message when serializing Python objects into JSON format.

Some of the common causes include:

  • Attempting to serialize a set object that consists of unserializable objects like functions or complex objects.
  • Using a custom object which is doesn’t define __dict__ method, which the JSON module uses to serialize objects.
  • Attempting to serialize a set object that consists of non-hashable objects.

Also, you may read the other resolve python error:

How to solve the typeerror object of type set is not json serializable?

Here are the few solutions you can try to follow to solve the typeerror object of type set is not json serializable.

Solution 1: Convert the Set Object into a List Object

The first solution to solve this error is to convert the set object into a list object, which is JSON serializable.

You can use the list() function to convert the set object into a list object, as follows:

For example:

import json

# Create a Python set object
my_set = {"apple", "banana", "cherry"}

# Convert the set object to a list object
my_list = list(my_set)

# Serialize the list object to a JSON formatted string
json_str = json.dumps(my_list)

# Print the serialized JSON string
print(json_str)

This code first creates a set object my_set that consists of three string elements.

Then it will convert my_set to a list object using the list() method and assigns the resulting list to my_list.

Next, the code serializes my_list into a JSON formatted string using the json.dumps() method and assigns the resulting string to json_str.

Finally, the code will print the serialized JSON string to the console.

The output should be a JSON-formatted string containing the elements of my_list.

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
[“cherry”, “apple”, “banana”]

Solution 2: Using a Custom Encoder Class

The second solution to solve the error is to use a custom encoder class that can manage the serialization of set objects.

You can create a custom encoder class that inherits from the json.JSONEncoder class and control the default() method to handle the serialization of set objects.

For example:

import json


class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj)


my_set = {'jude', 'glenn', 'elijah', 'caren'}

json_str = json.dumps(my_set, cls=SetEncoder)

print(json_str)
print(type(json_str))

Output:

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
[“glenn”, “caren”, “jude”, “elijah”]

In this example, we have modified the variable name my_set to a new set of fruit names.

The SetEncoder class is used to convert the set object into a JSON-compatible list object.

The json.dumps() function is used to convert the list object into a JSON string, which is stored in the json_str variable.

Finally, we print the JSON string and its data type using the print() function.

Solution 3: Convert the Set Object into a Dictionary Object

The third solution to solve this error is to Convert the Set Object into a Dictionary Object.

Then serialize the dictionary object using the json.dump() method.

You can use the enumerate() function to create a dictionary object from the set object.

Here’s an example code that demonstrates how to convert a Python set object into a dictionary object. Then it will serialize it into a JSON-formatted string using the json module:

import json

# Create a Python set object
my_set = {"glenn", "jude", "elijah"}

# Convert the set object to a dictionary object
my_dict = {i: list(my_set)[i] for i in range(len(my_set))}

# Serialize the dictionary object to a JSON-formatted string
json_str = json.dumps(my_dict)

# Print the serialized JSON string
print(json_str)

This code first creates a set object my_set that consists of three string elements.

Then it will convert my_set to a dictionary object my_dict using a dictionary comprehension that maps each element in the set to an index in a new list.

Next, the code serializes my_dict into a JSON-formatted string using the json.dumps() method and assign the result string to json_str.

Finally, the code will print the serialized JSON string to the console.

The output should be a JSON-formatted string containing the elements of my_dict.

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
{“0”: “cherry”, “1”: “banana”, “2”: “apple”}

Note: This useful if you need to serialize a set object into a JSON-formatted string yet you want to maintain the order of the elements.

Solution 4: Use the default keyword argument

The fourth solution to solve this error you can use the default keyword argument in the call to the json.dumps() method.

For example:

import json

my_set = {'w', 'x', 'y', 'z'}

json_list = json.dumps(my_set, default=list)

print(json_list)
print(type(json_list))

This code creates a set object my_set consisting of four string elements.

Then serializes the set object into a JSON-formatted string using the json.dumps() method and sets the default parameter to list.

This tells the method to use the list() function to serialize the set into a list object before encoding it as JSON.

The resulting JSON-formatted string is assigned to json_list, which is printed to the console along with its data type using the type() function.

The output should be a string that represents a JSON-encoded list of the elements in my_set in arbitrary order.

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
[“x”, “y”, “w”, “z”]

Solution 5: Use simplejson module to solve the error

The last solution to solve the error is that you can use simplejson module to solve the error.

You can do this by running the following command in your terminal or command prompt:

For PIP:

pip install simplejson

For PIP3:

pip3 install simplejson

Now you will be able to use the simplejson.dumps() method to serialize the set object.

For example:

import simplejson as json

my_set = {'w', 'x', 'y', 'z'}

json_list = json.dumps(my_set, iterable_as_array=True)

print(json_list) 
print(type(json_list))

Conclusion

In conclusion, the “TypeError: Object of type set is not JSON serializable” error occurs when you try to serialize a set object using the json.dump() or json.dumps() method.

The error message shows that the JSON module cannot serialize a set object into a JSON format.

We hope that in this article we provided you with the solutions will be able to solve the error you encountered in your Python projects.

FAQs

What is a set object in Python?

A set object in Python is an unordered collection of unique elements.

What are the benefits of using a custom encoder class in JSON serialization?

The benefits of using a custom encoder class in JSON serialization provides flexibility and customization in handling non-serializable objects or complex data structures.

Can you serialize other Python data types besides lists, dictionaries, and sets?

Yes, the json module in Python can serialize other data types such as integers, floats, strings, booleans, and tuples.