Convert a list of numpy arrays to json for return from flask api

Viewed 3149

I have a dictinary in python like this:

mydic = {
    'x1': list_of_numpy_array,
    'x2': a numpy_array,
    'x3': a list_of_numpy_array,
    'x4': a list_of_numpy_array
}

I want to send this dictionary from flask-api to the client which calss this api. When I use this code:

class GetRepresentationResource(Resource):
    url = 'representation'

    def get(self):
        # previous lines of my code which generates mydic
        return {
                'data': mydict,
                'err': ''
        }

I get the erro: Is not serializeable

2 Answers

I throw this error because np.array is not JSON serializable.

You need to convert each of them to a list before serializing

Try the following:


for k,v in mydict.items():
  if(isinstance(v, np.ndarray)):
    mydict[k] =  v.tolist()

See this Repl.it .

Note here that you would need to ensure that the types in the array are serializable

Note that JSON is ASCII, which means you will have to go through the pain of converting quite efficient binary data to ASCII. If your client also works with binary data you will have to do the opposite in the other end. There are optimized libraries for that, but if you have to convert back and forth and you are working with big binary data it may make more sense to return the files as blobs, of parquet or bson, for instance.

Related