The “typeerror: object of type ndarray is not json serializable” is an error message in Python.
Are you struggling to fix this error? Especially if you don’t have any idea how to resolve it.
So keep on reading!
This is because in this article we’ll delve into how to fix this “object of type ndarray is not json serializable“ error message.
What is “typeerror: object of type ndarray is not json serializable”?
The “typeerror object of type ndarray is not json serializable” occurs when you are trying to convert a NumPy array to a JSON string.
This error occurs mainly because ndarray is not a suitable type for JSON serialization.
In addition to that, the ndarray object cannot be converted to a JSON format due to its complex data type.
For example:
import numpy as np
import json
# Creating a NumPy ndarray
my_array = np.array([1, 2, 3,4, 5])
# Trying to convert the ndarray to JSON
json_array = json.dumps(my_array)
As a result, it will throw an error message:
TypeError: Object of type ndarray is not JSON serializableJSON is a text-based format for exchanging data between applications, and it can only handle a limited set of data types such as:
✔ strings
✔ numbers
✔ booleans
✔ null
✔ arrays
✔ objects
✔ dictionaries
Why does this “object of type ndarray is not JSON serializable” type error occur?
The following are the various reasons why this error occurs in your Python script:
→ serialization of the ndarray
→ invalid data types
→ infinite or NaN values
→ complex numbers
How to fix “typeerror: object of type ndarray is not json serializable”?
Here are the following solutions you may use to resolve the type error:
1: Use tolist() method
You can simply converts the ndarray to a Python list using the tolist() method.
And then serializes the list using the json.dumps() method.
import numpy as np
import json
# Creating a NumPy ndarray
sample_array = np.array([10, 20, 30, 40, 50])
# Converting the ndarray to a list
my_list = sample_array.tolist()
# Converting the list to JSON
json_array = json.dumps(my_list)
print(json_array)Output:
[10, 20, 30, 40, 50]
2: Use a custom encoder
Using a custom encoder class you can handle ndarrays and fix the error
import numpy as np
import json
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
arr = np.array([10, 20, 30, 40, 50])
json_str = json.dumps(arr, cls=NumpyEncoder)
print(json_str)
As you can see in this solution, it defines a custom encoder class that checks if the object being encoded is an ndarray and converts it to a list using tolist().
Output:
[10, 20, 30, 40, 50]3: Extend the JSONEncoder class
You can also extend the JSONEncoder class and use the default() method to handle the conversions.
That return the serializable object.
import json
import numpy as np
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
arr = np.array([10, 20, 30, 40, 50])
json_str = json.dumps({'sample': arr}, cls=NpEncoder)
print(json_str)
print(type(json_str))
Output:
{"sample": [10, 20, 30, 40, 50]}
<class 'str'>4: Use default keyword
Alternatively, you can use the “default” keyword argument to call the “json.dumps()” method.
import json
import numpy as np
def json_serializer(obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return obj
arr = np.array([10, 20, 30, 40, 50])
json_str = json.dumps({'sample': arr}, default=json_serializer)
print(json_str)
Output:
{"sample": [10, 20, 30, 40, 50]}5: Use panda’s library
You can use the “Pandas” library to convert the NumPy array into a DataFrame and then serialize it as a JSON object.
Also, you can resolve the error using the to_json() method.
import numpy as np
import pandas as pd
arr = np.array([10, 20, 30, 40, 50])
json_str = pd.Series(arr).to_json(orient='values')
print(json_str)
Output:
[10,20,30,40,50]6: Convert ndarray to a dictionary
To resolve the error, you can convert the ndarray to a dictionary with the desired format and then serialize the dictionary using the json.dumps() method.
import numpy as np
import json
arr = np.array([10, 20, 30, 40, 50])
arr_dict = {"dtype": str(arr.dtype), "data": arr.tolist()}
json_str = json.dumps(arr_dict)
print(json_str)
Output:
{"dtype": "int32", "data": [1, 2, 3]}Conclusion
In conclusion, the “typeerror object of type ndarray is not json serializable” occurs when you are trying to convert a NumPy array to a JSON string.
Fortunately, this article provided several solutions above so that you can fix the “object of type ndarray is not json serializable” error message.
We are hoping that this article provided you with sufficient solutions to get rid of the error.
You could also check out other “typeerror” articles that may help you in the future if you encounter them.
- Typeerror: res.status is not a function
- Typeerror: method object is not subscriptable
- Typeerror object of type decimal is not json serializable
Thank you very much for reading to the end of this article.
Python TypeError debugging checklist
- Read the full traceback. The bottom line is the error type + message. The line above shows the exact code that triggered it.
- Print types. Insert
print(type(x), type(y))before the error line to see what Python actually has. - Use isinstance. Guard code with
if isinstance(x, expected_type):. - Type hints + mypy. Adding
x: intlets mypy catch mismatches before you run the code. - Break into a debugger. Insert
breakpoint()before the failing line and inspect variables live.
Common root causes across all TypeError variants
- Silent None returns. A function that should have returned a value returned None instead.
- Mixing types across function boundaries. Legacy code passing str where int is expected (or vice versa).
- Shadowed builtins. Local variable named list, dict, set overriding the built-in.
- Optional[T] not handled. Callers not accounting for the None case.
- Third-party library API drift. New version renamed a kwarg or changed a return type.
Modern tooling to prevent TypeError
- Type hints (PEP 484+). Optional[X], Union[X,Y], List[T] make expected types explicit.
- mypy or Pyright. Runs your codebase through a type checker before you run it.
- Ruff. Fast linter that catches many TypeError-adjacent bugs.
- pydantic v2. Runtime validation with the same syntax as static types.
- pytest fixtures. Test each function with edge-case inputs to catch TypeError paths early.
Official documentation
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.
