Saturday, November 16, 2024
Google search engine
HomeLanguagesFix Type Error : NumPy array is not JSON serializable

Fix Type Error : NumPy array is not JSON serializable

In this article, we will see how to fix TypeError: Object of type ndarray is not JSON serializable when we are converting a NumPy ndarray object to a JSON string.

What is “TypeError: Object of type ndarray is not JSON serializable”?

The error “TypeError: Object of type ndarray is not JSON serializable” generally occurs in Python when we are converting a NumPy ndarray object to a JSON String. In this example, the demonstration of this error is shown below.

Python3




import json
import numpy as np
 
arr = np.array([1, 2, 3])
 
#TypeError: Object of type ndarray is not JSON serializable
json_str = json.dumps({'nums': arr})


Output

TypeError: Object of type ndarray is not JSON serializable

Type Error: NumPy Array is not JSON Serializable

Below are the ways by which we can fix this error and handle the conversion of ndarray object to a JSON string.

Using tolist() to fix TypeError

A crucial function provided by Python NumPy, which is used to convert array to list is known as tolist() function. In this way, we will see how we can fix the Type Error: NumPy array is not JSON serializable by converting NumPy array to list. In this example, we are using tolist() to convert NumPy Array to list.

Python3




# Python program to Fix Type Error : NumPy array is not
# JSON serializable converting NumPy array to list
import json
import numpy as np
 
# Create a NumPy array
array = np.array([7, 4, 2])
 
# Serialize JSON after converting NumPy array to list
arr_json = json.dumps({'nums': array.tolist()})
 
# Print the serialized JSON
print(arr_json)


Output

Screenshot-2023-09-20-233010

Extending the JSONEncoder class

The other way of fixing the type error: NumPy array is not JSON serializable, is by creating a function inside a class, and call that class while serializing the JSON. This function will convert NumPy array to JSON. In this example, we are extending the JSONEncoder class to fix this error.

Python3




# Import the libraries json and numpy
import json
import numpy as np
 
# Create a JSON Encoder class
class json_serialize(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)
 
# Create a NumPy array
array = np.array([7, 4, 2])
 
# Serialize JSON by calling JSON Encoder class
json_array = json.dumps({'nums': array}, cls=json_serialize)
 
# Print the serialized JSON
print(json_array)


Output

Screenshot-2023-09-20-233010

Using the default keyword argument

The json.dumps() offers various parameters out of which default is the significant parameter which helps in JSON serializing the NumPy array. In this way, we will see how can we JSON serialize NumPy array and fix Type Error: NumPy array is not JSON serializable by using default keyword argument. In this example, we are using default keyword to solve this error.

Python3




# Import the libraries json and numpy
import json
import numpy as np
 
# Create a function to be called while serializing JSON
def json_serialize(obj):
    if isinstance(obj, np.ndarray):
        return obj.tolist()
    return obj
 
# Create a NumPy array
array = np.array([7, 4, 2])
 
# Serialize JSON by using default keyword
json_array = json.dumps({'nums': array}, default=json_serialize)
 
# Print the serialized JSON
print(json_array)


Output

Screenshot-2023-09-20-233010

Using pandas library

Pandas is the library which is commonly used for working with datasets. A crucial function offered by Pandas is Series(), which is like a 1D array and can hold data of any type. In this way, we will see how can we JSON serialize NumPy array and fix Type Error: NumPy array is not JSON serializable by using Pandas Series function. In this example, we are using pandas library to solve this error.

Python3




# Import the libraries NumPy and Pandas
import numpy as np
import pandas as pd
 
# Create a NumPy array
array = np.array([7, 4, 2])
 
# Serialize JSON by using Pandas
json_array = pd.Series(array).to_json(orient='values')
 
# Print the serialized JSON
print('{"nums": ' +json_array+'}')


Output

Screenshot-2023-09-20-233010

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments