在创建NumPy数组后,并将其保存为Django上下文变量,我在加载网页时收到以下错误:
array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64) is not JSON serializable
这是什么意思?
在创建NumPy数组后,并将其保存为Django上下文变量,我在加载网页时收到以下错误:
array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64) is not JSON serializable
这是什么意思?
当前回答
如果其他人的代码(例如模块)正在执行json.dumps(),其他答案将不起作用。这种情况经常发生,例如,web服务器自动将其返回响应转换为JSON,这意味着我们不能总是更改JSON .dump()的参数。 这个答案解决了这个问题,并且基于一个(相对)新的解决方案,适用于任何第三方类(不仅仅是numpy)。
TLDR
PIP安装json_fix
import json_fix # import this anytime before the JSON.dumps gets called
import json
# create a converter
import numpy
json.fallback_table[numpy.ndarray] = lambda array: array.tolist()
# no additional arguments needed:
json.dumps(
dict(thing=10, nested_data=numpy.array((1,2,3)))
)
#>>> '{"thing": 10, "nested_data": [1, 2, 3]}'
其他回答
如果其他人的代码(例如模块)正在执行json.dumps(),其他答案将不起作用。这种情况经常发生,例如,web服务器自动将其返回响应转换为JSON,这意味着我们不能总是更改JSON .dump()的参数。 这个答案解决了这个问题,并且基于一个(相对)新的解决方案,适用于任何第三方类(不仅仅是numpy)。
TLDR
PIP安装json_fix
import json_fix # import this anytime before the JSON.dumps gets called
import json
# create a converter
import numpy
json.fallback_table[numpy.ndarray] = lambda array: array.tolist()
# no additional arguments needed:
json.dumps(
dict(thing=10, nested_data=numpy.array((1,2,3)))
)
#>>> '{"thing": 10, "nested_data": [1, 2, 3]}'
这是一个不同的答案,但这可能有助于那些试图保存数据然后再次读取的人。 有一种方法比泡菜更快更容易。 我试图保存并在pickle dump中阅读它,但在阅读时有很多问题,浪费了一个小时,尽管我正在用自己的数据创建一个聊天机器人,但仍然没有找到解决方案。
Vec_x和vec_y是numpy数组:
data=[vec_x,vec_y]
hkl.dump( data, 'new_data_file.hkl' )
然后你只需读取它并执行以下操作:
data2 = hkl.load( 'new_data_file.hkl' )
我经常“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)
我有一个类似的问题,嵌套字典与一些numpy。ndarray在里面。
def jsonify(data):
json_data = dict()
for key, value in data.iteritems():
if isinstance(value, list): # for lists
value = [ jsonify(item) if isinstance(item, dict) else item for item in value ]
if isinstance(value, dict): # for nested lists
value = jsonify(value)
if isinstance(key, int): # if key is integer: > to string
key = str(key)
if type(value).__module__=='numpy': # if value is numpy.*: > to python list
value = value.tolist()
json_data[key] = value
return json_data
你可以使用Pandas:
import pandas as pd
pd.Series(your_array).to_json(orient='values')