美文网首页
解决:TypeError: Object of type xxx

解决:TypeError: Object of type xxx

作者: 风筝flying | 来源:发表于2019-05-17 17:16 被阅读0次

    问题描述

    在导入Python json包,调用json.dump/dumps函数时,可能会遇到TypeError: Object of type xxx is not JSON serializable错误,也就是无法序列化某些对象格式。

    解决办法

    自定义序列化方法

    class MyEncoder(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()
            if isinstance(obj, time):
                return obj.__str__()
            else:
                return super(NpEncoder, self).default(obj)
    

    然后在调用json.dump/dumps时,指定使用自定义序列化方法

    json.dumps(data, cls=MyEncoder) 
    

    相关文章

      网友评论

          本文标题:解决:TypeError: Object of type xxx

          本文链接:https://www.haomeiwen.com/subject/zfwoaqtx.html