TypeError: Object of type ‘ndarray‘ is not JSON serializable

对于python中的字典数据的读写问题,一种常见的方法是通过json包来对其进行读写。

但是当字典中的数据包含ndarry对象时,直接利用json包读写时,会报TypeError: Object of type ‘ndarray‘ is not JSON serializable的错误。

这是因为ndaary对象类型无法进行json序列化。解决办法就是继承json.JSONEncoder,对其中的default方法进行重写,增加对numpy中的对象进行序列化的操作。

具体实现如下:

import numpy as np
import json
import codecs
parameters = {
    
    'w1': np.arange(10), 'w2': np.array([[1, 2, 3], [3, 2, 1]])}
class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)


# 字典写入文件
with codecs.open("./para_new.csv", 'w', encoding='utf-8') as f:
    json.dump(parameters, f, cls=NpEncoder)

# 读取字典
file = open("./para_new.csv", 'r')
js = file.read()
dict_num = json.loads(js)

# 读取的数据,由于序列化操作,所以ndarry对象变为了list对象
print(type(dict_num['w1']))


# 将字典中的数据类型,变为原来的格式
for i in dict_num.keys():
    dict_num[i] = np.array(dict_num[i])

print(type(dict_num['w1']))

运行结果
在这里插入图片描述
其中关于ndarry对象的tolist方法,可以参考我的这篇博客https://blog.csdn.net/qq_38048756/article/details/107798597

参考:
https://blog.csdn.net/mochou111/article/details/100984538
https://blog.csdn.net/qq_29631521/article/details/103169161

猜你喜欢

转载自blog.csdn.net/qq_38048756/article/details/114139793
今日推荐