更新时间:2022-11-22 20:46:02
我经常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()
/ pre>
b_new = json.loads(obj_text)
a_new = np.array(b_new)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)