当前位置:   article > 正文

Python3.x中json.dumps报TypeError: Object of type ‘bytes‘ is not JSON serializable

Python3.x中json.dumps报TypeError: Object of type ‘bytes‘ is not JSON serializable

mat文件用python读取数据之后,得到一个字典数组,笔者想将这个字典数组储存到json文件中,因此应该先编码json数据,因此用到了json.dumps函数进行编码,但是我使用json.dumps函数时发现有会出现问题:

TypeError: Object of type 'bytes' is not JSON serializable

后来查阅相关资料才发现,默认的编码函数很多数据类型都不能编码,因此可以自己写一个encoder去继承jsonencoder ,这样就能够进行编码了。

    比如说上面的这个问题,是因为json.dumps函数发现字典里面有bytes类型的数据,因此无法编码,只要在编码函数之前写一个编码类(继承原本的JSONEncoder类),并在编码的时候使用这个类,只要检查到了是bytes类型的数据就把它转化成str类型。

  1. class MyEncoder(json.JSONEncoder):
  2. def default(self, obj):
  3. if isinstance(obj, bytes):
  4. return str(obj, encoding='utf-8');
  5. return json.JSONEncoder.default(self, obj)

这样就解决了这个问题。

    后面在编码的时候发现出现类似问题:

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

 

    这样也是一样的处理方式,当检查到了ndarray数据,把它转化成list数据就行:

  1. class MyEncoder(json.JSONEncoder):
  2. def default(self, obj):
  3. if isinstance(obj, np.ndarray):
  4. return obj.tolist()
  5. elif isinstance(obj, bytes):
  6. return str(obj, encoding='utf-8');
  7. return json.JSONEncoder.default(self, obj)

    这样就编码好了数据了。

Final:

import scipy.io as sio
import os
import json
import numpy as np
 
load_fn = '2%.mat'
load_data = sio.loadmat(load_fn)
print(load_data.keys())
 
class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8');
        return json.JSONEncoder.default(self, obj)
 
save_fn = os.path.splitext(load_fn)[0] + '.json'
file = open(save_fn,'w',encoding='utf-8');
file.write(json.dumps(load_data,cls=MyEncoder,indent=4))
file.close()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/348728
推荐阅读
  • 相关标签
      

    闽ICP备14008679号