python - NumPy 数组不是 JSON 可序列化的

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

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

这是什么意思?

最佳答案

我经常“jsonify”np.arrays。首先尝试在数组上使用“.tolist()”方法,如下所示:

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

为了“unjsonify”数组使用:

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

https://stackoverflow.com/questions/26646362/

相关文章:

json - HTTP 中的 "406-Not Acceptable Response"是什么?

javascript - jQuery为ajax请求返回 "parsererror"

c# - 将 JSON 字符串转换为 C# 对象

java - 在 Java 中使用 JSON 的 HTTP POST

json - 如何使用 JSON 对象初始化 TypeScript 对象?

json - 如何通过 JSON 文件传递​​有效载荷以进行 curl?

json - JSON 语法是否允许对象中有重复的键?

java - 将 JSON 转换为 map

java - 如何指定 jackson 只使用字段 - 最好是全局

c# - 在序列化 'SubSonic.Schema .DatabaseColumn' 类型的对象时