Tutorial Example

Fix TypeError: Object of type ‘ndarray’ is not JSON serializable – Python Tutorial

In this tutorial, we will use an example to show you how to fix TypeError: Object of type ‘ndarray’ is not JSON serializable in python.

Look at example below:

import numpy as np
import json

data= {}
data["vector"] = np.random.random((10,))

print(json.dumps(data))

Run this code, you will get this error:

How to fix this error?

We should convert ndarray to python list. Here is a solution.

data["vector"] = np.random.random((10,)).tolist()

print(json.dumps(data))

Run this code, you will get this output:

{"vector": [0.0033196112440357917, 0.6680030275423572, 0.4622229452216984, 0.7155292384011634, 0.6427014520255453, 0.5984720076720726, 0.5005050868254417, 0.8623587301379475, 0.9350345421948418, 0.012840594106745096]}

It means this error is fixed.

To understand more on python object to string, you can read:

Serialize Python Object to String and Deserialize It to Object for Python Beginners – Python Tutorial