zoukankan      html  css  js  c++  java
  • Object of type datetime/Decimal is not JSON serializable

     python使用json.dumps()方法把字典序列化成字符串,如果报错Object of type datetime/Decimal is not JSON serializable。那么往往是需要专门类型的编码器。
    比如,如果报错:Object of type datetime is not JSON serializable。那么需要创建一个DateEncoder类,专门给Date对象编码,
     
    TypeError: Object of type datetime is not JSON serializable
    1 class DateEncoder(json.JSONEncoder):
    2     def default(self, obj):
    3         if isinstance(obj, datetime):
    4             return obj.strftime('%Y-%m-%d %H:%M:%S')
    5         elif isinstance(obj, date):
    6             return obj.strftime("%Y-%m-%d")
    7         else:
    8             return json.JSONEncoder.default(self, obj)
    使用方法,在json.dumps()方法中增加一个参数cls, 赋值为你写得编码类
    json_str = json.dumps(obj, cls=DateEncoder)
    后来又碰到到Decimal不可序列化的问题:TypeError: Object of type Decimal is not JSON serializable.
    我想应该也是写个DecimalEncoder类来为Decimal类型编码,但是因为有DecimalEncoder和DateEncoder两个编码类,所以不知道该怎么给dumps()方法传参,百度了好久怎么给dumps()方法传递多个编码器,但是都没找到方法,看来这个方法只能接受一个编码器。后来想到可以把多个编码器写在同一个类里面。比如下面这个DateEncoder就同时是Decimal和Date两种类型编码器,如果还有其他编码类型,在后面继续添加if else即可。
    class DateEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime.datetime):
                return obj.strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(obj, datetime.date):
                return obj.strftime("%Y-%m-%d")
            elif isinstance(obj, decimal.Decimal):
                return float(obj)
            else:
                return json.JSONEncoder.default(self, obj)
    参考:
     
  • 相关阅读:
    修复TabControl在Binding情况下Canvas被复用的问题
    避免缓加载时因违反惯例导致的空引用!
    乱说一气
    WPF中的数据验证
    [zz]GPU architecture
    [zz]DirectX 11 and Shared Model 5.0
    网页栅格系统中的最佳宽度:960px
    复习html标签及其属性
    去除链接虚线边框css
    使用jquery解决IE6不兼容的伪类
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/14970539.html
Copyright © 2011-2022 走看看