Fix Type Error : NumPy array is not JSON serializable
Last Updated :
02 Oct, 2023
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 ])
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
import json
import numpy as np
array = np.array([ 7 , 4 , 2 ])
arr_json = json.dumps({ 'nums' : array.tolist()})
print (arr_json)
|
Output
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 json
import numpy as np
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)
array = np.array([ 7 , 4 , 2 ])
json_array = json.dumps({ 'nums' : array}, cls = json_serialize)
print (json_array)
|
Output
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 json
import numpy as np
def json_serialize(obj):
if isinstance (obj, np.ndarray):
return obj.tolist()
return obj
array = np.array([ 7 , 4 , 2 ])
json_array = json.dumps({ 'nums' : array}, default = json_serialize)
print (json_array)
|
Output
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 numpy as np
import pandas as pd
array = np.array([ 7 , 4 , 2 ])
json_array = pd.Series(array).to_json(orient = 'values' )
print ( '{"nums": ' + json_array + '}' )
|
Output
Share your thoughts in the comments
Please Login to comment...