Typeerror: object of type ndarray is not json serializable

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 serializable

JSON 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.

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