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.
| Python | JSON |
| list, tuple | array |
| int, long, float | number |
| dict | object |
| str | string |
| None | null |
| True | true |
| False | false |
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.
- Typeerror cannot read property ‘map’ of undefined
- Typeerror cannot set properties of undefined
- Typeerror: ‘column’ object is not callable
Thank you very much for reading to the end of this article.
Official documentation
Featured guides worth reading next
Quick step-by-step summary (click to expand)
- Identify the non-serializable type. Read the error message. The type is right there (Decimal, datetime, set, ndarray, UUID). That is the value you need to convert.
- Convert to a JSON-compatible type. Cast the value before dumping. Decimal to float, datetime to isoformat string, set to list, ndarray to .tolist().
- Use the default= parameter on json.dumps. Pass default=str to fall back to string for any unknown type. Fast fix but you lose precision on numbers.
- Subclass json.JSONEncoder for a permanent fix. Write a custom encoder class that handles your specific types in one place. Pass it via cls=YourEncoder to json.dumps.
Frequently Asked Questions
What is Python TypeError and what causes it?
TypeError is raised when an operation is applied to an object of the wrong type. Common patterns: calling a non-callable object, adding incompatible types (str + int), passing the wrong number of arguments, or accessing attributes on a NoneType. Each TypeError message names the operation and expected vs actual types, the fix is almost always to convert types explicitly (int(), str()) or fix the wrong variable assignment.
How do I quickly debug a Python TypeError?
Three steps: (1) Read the full error message, it names the exact operation and types involved. (2) Print the type of every variable in that line: print(type(var1), type(var2)). (3) Check what the function expected vs what you passed. Most TypeError fixes are 1-line type casts or fixing a variable that became None unexpectedly.
Should I catch TypeError or let it propagate?
For internal code, let TypeError propagate, it’s almost always a real bug (wrong type passed). For boundary code (parsing user input, third-party API responses), catch TypeError + ValueError together: try: parsed = int(value) except (TypeError, ValueError): parsed = 0. Catching internal TypeErrors hides bugs.
How do I prevent TypeError in production?
Three patterns: (1) Use type hints (def add(a: int, b: int) -> int) and check with mypy / pyright in CI. (2) Validate inputs at boundaries (Pydantic for FastAPI, DRF serializers for Django). (3) Default values that match expected types (return 0 not None for numeric functions). Static typing catches 80% of TypeErrors before runtime.
Where can I find more TypeError fixes?
Browse the TypeError reference hub for 220+ specific TypeError fixes. For broader Python debugging, see the Python Tutorial hub. For related error types, see ValueError and AttributeError guides.
