Nono.MA

NOVEMBER 12, 2022

If you try to serialize a NumPy array to JSON in Python, you'll get the error below.

TypeError: Object of type ndarray is not JSON serializable

Luckily, NumPy has a built-in method to convert one- or multi-dimensional arrays to lists, which are in turn JSON serializable.

import numpy as np
import json

# Define your NumPy array
arr = np.array([[100,200],[300,400]])

# Convert the array to list
arr_as_list = arr.tolist()

# Serialize as JSON
json.dumps(arr_as_list)
# '[[100, 200], [300, 400]]'

NOVEMBER 11, 2022

Here's the error I was getting when trying to return a NumPy ndarray in the response body of an AWS Lambda function.

Object of type ndarray is not JSON serializable

Reproduce the error

import numpy as np
import json

# A NumPy array
arr = np.array([[1,2,3],[4,5,6]])
        .astype(np.float64)

# Serialize the array
json.dumps(arr)
# TypeError: Object of type ndarray is not JSON serializable

Solution

NumPy arrays provide a built-in method to convert them to lists called .tolist().

import numpy as np
import json

# A NumPy array
arr = np.array([[1,2,3],[4,5,6.78]])
        .astype(np.float64)

# Convert the NumPy array to a list
arr_as_list = arr.tolist()

# Serialize the list
json.dumps(arr_as_list)

Want to see older publications? Visit the archive.

Listen to Getting Simple .