将 numpy 数组列表转换为 json 以从 Flask api 返回

use*_*968 7 python serialization json numpy flask-restful

我在 python 中有一个这样的字典:

mydic = {
    'x1': list_of_numpy_array,
    'x2': a numpy_array,
    'x3': a list_of_numpy_array,
    'x4': a list_of_numpy_array
}
Run Code Online (Sandbox Code Playgroud)

我想将此字典发送给flask-api调用此 api 的客户端。当我使用此代码时:

class GetRepresentationResource(Resource):
    url = 'representation'

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

我得到错误: Is not serializeable

Chi*_*ere 0

我抛出此错误是因为 np.array 不可 JSON 序列化。

您需要在序列化之前将它们每个都转换为列表

请尝试以下操作:


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

Run Code Online (Sandbox Code Playgroud)

请参阅此 Repl.it

请注意,您需要确保数组中的类型是可序列化的