Typeerror object of type is not json serializable

How to fix the “typeerror object of type is not json serializable” error message?

In this article, we will guide you on how to troubleshoot this error message that gives you a headache.

The “python object of type is not json serializable” error is quite frustrating, especially if you’re familiar with it and don’t know how to fix it.

This article is indeed for you, so keep on reading because we will discuss what this error means and the root causes.

What is JSON serializable?

A JSON serializable refers to data that can be converted to a JSON format without any issues.

JSON stands for JavaScript Object Notation.

JSON is a widely used format for data exchange, particularly in web applications.

It can represent simple data types such as strings and numbers, as well as complex data types such as lists and dictionaries.

However, not all Python objects can be directly serialized to JSON.

If you encounter this error message, it means that you are attempting to convert an object of an unsupported type to JSON.

You’ll see in the table below how the native Python objects are translated to JSON.

PythonJSON
list, tuplearray
int, long, floatnumber
dictobject
strstring
None null
Truetrue
Falsefalse

What is “typeerror object of type is not json serializable”?

The “typeerror: object of type is not JSON serializable” is an error message that occurs when you try to serialize an object to JSON format, but the object type is not supported by the JSON encoder.

In a simple words, the object is not “JSON serializable”.

In addition to that, this error occurs when you try to serialize an object that is not JSON serializable using the json.dump() or json.dumps() method.

Why does this error “object of type is not json serializable” occur?

This error occurs for several reasons, such as:

  • The input data contains a data type that is not JSON serializable, such as sets, complex numbers, or custom objects.
  • The input data contains a circular reference, where two or more objects refer to each other in a way that forms an infinite loop.
  • The input data contains a datetime object that is not JSON serializable. Datetime objects need to be converted to a string format before they can be serialized to JSON.
  • The input data contains a NumPy array or other non-Python object that is not JSON serializable.
  • The input data contains a subclass of a built-in Python type that is not JSON serializable.
  • For example, if you define a custom class that inherits from the dict class, you need to ensure that the class is JSON serializable.
  • The input data contains a function or other callable object that is not JSON serializable.

How to fix “typeerror object of type is not json serializable”?

To fix this “python object of type is not json serializable” error, you need to either remove the non-serializable data from the input, convert it to a JSON-serializable data type, or use a custom function that can properly serialize the data.

Here are the following solutions you may use to resolve the “object of type is not json serializable” error message:

1. Remove non-serializable data from the input

You have define a remove_non_serializable function that removes any non-serializable data types and converts the set object to a list.

import json
from collections import OrderedDict

data = {
    'website': 'Itsourcecode',
    'Visits': 18000000,
    'Offers': {'free sourcecode and tutorials'}
}

def remove_non_serializable(obj):
    if isinstance(obj, set):
        return list(obj)
    return obj

json_data = json.dumps(OrderedDict((k, remove_non_serializable(v)) for k, v in data.items()))
print(json_data)

Output:

{"website": "Itsourcecode", "Visits": 18000000, "Offers": ["free sourcecode and tutorials"]}

2.Convert non-serializable data types to JSON-serializable types

In this example, the data dictionary contains a datetime object, which is not JSON-serializable.

So, we just define a json_serializable function that converts the datetime object to a string representation using the __str__() method.

import json
from datetime import datetime

data = {
    'website': 'Itsourcecode',
    'Visits': 18000000,
    'Offers': 'free sourcecode and tutorials',
    'dob': datetime.now()

}

def json_serializable(obj):
    if isinstance(obj, datetime):
        return obj.__str__()

print(json.dumps(data, default=json_serializable))

Then pass this function as the default parameter to the json.dumps() function, which converts the datetime object to a string representation and serializes the entire dictionary into JSON format.

Output:

{"website": "Itsourcecode", "Visits": 18000000, "Offers": "free sourcecode and tutorials", "dob": "2023-04-14 15:56:35.558356"}

3. Use custom function to handle non-serializable objects

You have to define a custom encoder that can handle non-serializable data types.

You can do this by subclassing the json.JSONEncoder class and overriding the default() method to provide a custom serialization method for your non-serializable data.

import json

# Define a custom encoder class
class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        elif isinstance(obj, complex):
            return {'real': obj.real, 'image': obj.imag}
        else:
            return super().default(obj)

# Define a dictionary with non-serializable data
my_dict = {'my_set': {1, 2, 3}, 'my_complex': 1 + 2j}

# Serialize the dictionary with the custom encoder
serialized_data = json.dumps(my_dict, cls=MyEncoder)
print(serialized_data)

Output:

{"my_set": [1, 2, 3], "my_complex": {"real": 1.0, "image": 2.0}}

Conclusion

By executing all the effective solutions for the “typeerror object of type is not json serializable” that this article has already provided above, it will help you resolve the error.

We are hoping that this article provides you with sufficient solutions.

You could also check out other “typeerror” articles that may help you in the future if you encounter them.

Thank you very much for reading to the end of this article.