Python-Json异常:Object of type Decimal is not JSON serializable

发布时间 2023-10-21 21:37:06作者: 青塬科技

源起:

使用python分离出一串文本,因为是看起来像整数,结果json转换时发生异常:TypeError: Object of type Decimal is not JSON serializable

msgInfo={"uid":3232324232}
json.dumps(msgInfo, ensure_ascii=False)

原因:

decimal格式不能被json.dumps正确处理。json.dumps函数发现字典里面有 Decimal类型的数据,无法JSON serializable

同样的问题也会出现在转换bytes数据时。

解决办法:

解决方法:是检查到Decimal类型的值转化成float类型

对于bytes则需要做一层编码。

正好为了防止中文出错,每次解析加ensure_ascii挺麻烦的。如果不加ensure_ascii,很多时候中文会被转译为:"\u4e2d\u56fd"这样的格式。

原因在于python序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False。

顺手封装为一个公共函数。方便使用。

顺手把时间 转换和bytes处理也一并加上。

后面直接使用toJson(data)就可以。


def toJson(data, indent=None):
    """
    数据转换为Json。
    :param data:
    :param indent:
    :return:
    """
    return json.dumps(data, cls=CustomJsonEncoder, ensure_ascii=False, indent=indent)


class CustomJsonEncoder(json.JSONEncoder):
    """
    Json解析器,解决识别Decimal出错的问题
    """

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        if isinstance(obj, int):
            return int(obj)
        elif isinstance(obj, float):
            return float(obj)
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        # elif isinstance(obj, array):
        #    return obj.tolist()
        else:
            return super(CustomJsonEncoder, self).default(obj)

同open读文件一样,python对很多问题貌似并不太符合我们的中文习惯。每次都需要加上encoding='utf-8'不然常常会读中文内容时出现问题。

本文由博客一文多发平台 OpenWrite 发布!