NumPy数组不是JSON可序列化的 [英] NumPy array is not JSON serializable

查看:958
本文介绍了NumPy数组不是JSON可序列化的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建NumPy数组并将其保存为Django上下文变量后,加载网页时收到以下错误:

  array([0,239,479,717,952,1192,1432,1667],dtype = int64)不是JSON可序列化

这是什么意思?

解决方案

我经常jsonifynp.arrays。尝试使用数组上的.tolist()方法,如下所示:

  import numpy as np 
导入编解码器,json

a = np.arange(10).reshape(2,5)#a 2乘5数组
b = a.tolist()#嵌套列表具有相同的数据,索引
file_path =/path.json##您的路径变量
json.dump(b,codecs.open(file_path,'w',encoding ='utf-8'),separatorators =(' ,',':'),sort_keys = True,indent = 4)###将数组以.json格式保存

为了unjsonify数组使用:

  obj_text = codecs.open(file_path,'r ',encoding ='utf-8')read()
b_new = json.loads(obj_text)
a_new = np.array(b_new)
/ pre>

After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:

array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) is not JSON serializable

What does this mean?

解决方案

I regularly "jsonify" np.arrays. Try using the ".tolist()" method on the arrays first, like this:

import numpy as np
import codecs, json 

a = np.arange(10).reshape(2,5) # a 2 by 5 array
b = a.tolist() # nested lists with same data, indices
file_path = "/path.json" ## your path variable
json.dump(b, codecs.open(file_path, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4) ### this saves the array in .json format

In order to "unjsonify" the array use:

obj_text = codecs.open(file_path, 'r', encoding='utf-8').read()
b_new = json.loads(obj_text)
a_new = np.array(b_new)

这篇关于NumPy数组不是JSON可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆