Nono.MA

Return a NumPy ndarray from AWS Lambda

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)

BlogTilPythonNumpy