TypeError: NumPy array is not JSON serializable [FIXED]

The error message you’re encountering, “TypeError: NumPy array is not JSON serializable,” typically occurs when you try to serialize a NumPy array directly into JSON format. JSON (JavaScript Object Notation) is a lightweight data interchange format, and not all data types can be directly converted into JSON.

To resolve this issue, you need to convert the NumPy array into a JSON serializable format before serializing it into JSON. Here’s a general approach to do that:

  1. Convert the NumPy array into a Python list.
  2. Serialize the Python list into JSON.
Python
import numpy as np
import json

# Example NumPy array
numpy_array = np.array([1, 2, 3, 4, 5])

# Convert NumPy array to Python list
python_list = numpy_array.tolist()

# Serialize Python list to JSON
json_data = json.dumps(python_list)

# Now you can use the JSON data as needed
print(json_data)

In the above code:

  • numpy_array.tolist() converts the NumPy array into a Python list.
  • json.dumps() serializes the Python list into JSON format.

This way, you can avoid the TypeError related to serializing NumPy arrays directly into JSON.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart