如何将带有 numpy 数组的字典转换为 json 并返回?

Moh*_*adi 0 python arrays json numpy

我正在学习 python 开发,我是 python 世界的新手,下面是我的字典,其值为 NumPy 数组,我想将其转换为 JSON,然后将其从 JSON 转换回带有 NumPy 数组的字典。实际上,我正在尝试使用 json.dumps() 对其进行转换,但它给了我一个错误:ndarray 类型的对象不是 JSON 可序列化的

{
  'chicken': array([5. , 4. , 3. , 2. , 1. , 0.5, 0. ]),
  'banana': array([4. , 3. , 2. , 1. , 0.5, 0. ]),
  'carrots': array([5. , 4. , 3. , 2. , 1. , 0.5, 0. ]),
  'turkey': array([5. , 4. , 3. , 2. , 1. , 0.5, 0. ]),
  'rice': array([3. , 2. , 1. , 0.5, 0. ]),
  'whey': array([5. , 4. , 3. , 2. , 1. , 0.5, 0. ]),
  'peanut': array([5. , 4. , 3. , 2. , 1. , 0.5, 0. ]),
  'Yellow Cake (with Vanilla Frosting)': array([5. , 4. , 3. , 2. , 1. , 0.5, 0. ])
}
Run Code Online (Sandbox Code Playgroud)

我这样做是因为我想将数据从一个 AWS Lambda 函数传递到另一个 AWS Lambda 函数。任何帮助将不胜感激,谢谢。

muj*_*iga 6

numpy数组不能直接转换成json;而是使用列表。

# Test data
d = {
  'chicken': np.random.randn(5),
  'banana': np.random.randn(5),
  'carrots': np.random.randn(5)
}

# To json
j = json.dumps({k: v.tolist() for k, v in d.items()})

# Back to dict
a = {k: np.array(v) for k, v in json.loads(j).items()}

print (a)
print (d)
Run Code Online (Sandbox Code Playgroud)

输出:

{'banana': array([-0.9936452 ,  0.21594978, -0.24991611,  0.99210387, -0.22347124]),
 'carrots': array([-0.7981783 , -1.47840335, -0.00831611,  0.58928124, -0.33779016]),
 'chicken': array([-0.03591249, -0.75118824,  0.58297762,  0.5260574 ,  0.6391851 ])}

{'banana': array([-0.9936452 ,  0.21594978, -0.24991611,  0.99210387, -0.22347124]),
 'carrots': array([-0.7981783 , -1.47840335, -0.00831611,  0.58928124, -0.33779016]),
 'chicken': array([-0.03591249, -0.75118824,  0.58297762,  0.5260574 ,  0.6391851 ])}
Run Code Online (Sandbox Code Playgroud)