源起:

使用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 发布!

Python-Json异常:Object of type Decimal is not JSON serializable的更多相关文章

  1. Object of type Decimal is not JSON serializable

    json遇到Decimal 型数据无法正确处理 解决方案 import json result = [ {'name': '小红', 'age': 26, 'balance': decimal.Dec ...

  2. typeerror object of type ‘decimal‘ is not json serializable jsonify

    当使用flask的jsonify返回json数据时,由于数据库有些字段类型使用decimal,而jsonify无法处理 解决方案 导入下面的包即可解决 pip install simplejson

  3. celery 4.1下报kombu.exceptions.EncodeError: Object of type 'bytes' is not JSON serializable 处理方式

    #python代码如下 from celery import Celeryimport subprocess app = Celery('tasks', broker='redis://localho ...

  4. Object of type 'ListSerializer' is not JSON serializable “listserializer”类型的对象不可JSON序列化

    Object of type 'ListSerializer' is not JSON serializable “listserializer”类型的对象不可JSON序列化 一般原因为 序列化的对象 ...

  5. TypeError: Object of type 'int64' is not JSON serializable

    错误类型:TypeError: Object of type 'int64' is not JSON serializable 错误场景:对Numpy和Pandas结果进行json.dumps报错 错 ...

  6. TypeError: Object of type 'int32' is not JSON serializable ——已解决

    将模型用flask封装,返回json时报错:TypeError: Object of type 'int32' is not JSON serializable 网上搜索出的解决方案:重写json.J ...

  7. labelme2coco问题:TypeError: Object of type 'int64' is not JSON serializable

    最近在做MaskRCNN 在自己的数据(labelme)转为COCOjson格式遇到问题:TypeError: Object of type 'int64' is not JSON serializa ...

  8. Object of type 'ndarray' is not JSON serializable

    Object of type 'ndarray' is not JSON serializable import numpy as np import json arr=np.asarray([345 ...

  9. TypeError: Object of type 'int32' is not JSON serializable

    将模型用flask封装,返回json时报错:TypeError: Object of type 'int32' is not JSON serializable 网上搜索出的解决方案:重写json.J ...

  10. python 中的object与type的关系

    object 和 type的关系很像鸡和蛋的关系,先有object还是先有type没法说,obejct和type是共生的关系,必须同时出现的. 在看下去之前,也要请先明白,在Python里面,所有的东 ...

随机推荐

  1. minIO系列文章02---linux安装

    目录 1.Minio介绍 2.安装MinIO 3. MinIO客户端 1.Minio介绍MinIO 是一个基于Apache License v2.0开源协议的对象存储服务.适合于存储大容量非结构化的数 ...

  2. HTML直接插入js、css

    简单的小页面可以使用 代码量大的话还是建议引用代码 直接包裹起来 <style>这里添加css代码</style> 加入css标识 <style type="t ...

  3. NSSCTF Round#17 Basic CRYPTO

    Level_1 题目 Level_1.py(我把参数整理了一下,看着舒服) #真签到题 from Crypto.Util.number import bytes_to_long, getPrime f ...

  4. Asp .Net Core 部署在阿里云Centos上 :使用Docker部署

    参照 https://www.cnblogs.com/xiaxiaolu/p/9973631.html 运行环境 使用SecureCrt连接服务器 1.阿里云ECS 4核 16 GiB 8Mbps 带 ...

  5. 解决idea登录github出现的invalid authentication data 404 not found以及登录 token 失效

    0.错误提醒: Your token is invalid, please re-login github and get token again. 报错无效的用户名(invalid username ...

  6. 5.1 内存CRC32完整性检测

    CRC校验技术是用于检测数据传输或存储过程中是否出现了错误的一种方法,校验算法可以通过计算应用与数据的循环冗余校验(CRC)检验值来检测任何数据损坏.通过运用本校验技术我们可以实现对特定内存区域以及磁 ...

  7. Unity框架中的核心类

    组件:Component 在Unity中,所有的游戏对象都可以挂载组件.组件控制着游戏对象的行为和外观,例如渲染.动画.碰撞检测等. 而Component就是组件的基类,提供了一些通用的方法和属性,例 ...

  8. gitee 命令合集(从远程仓库拉取项目到推送项目到远程仓库)

    1.配置用户的信息 git config --global user.name '你的用户名' git config --global user.email '你的邮箱' 2.初始化 Git 仓库,生 ...

  9. C语言输出百分号%

    遭遇的问题 在学习时有一个课后题要求计算两个变量的加减乘除以及取余,其中去余需要输出如下的效果: 10 % 5 = 0; 我就写了这样的代码: printf("a % b = %d" ...

  10. 练习(Java):将一个数转换为16进制;获得多位数的各个位上的数

    //将一个数转换为十六进制 int num = 60; int i1 = num % 16; int i2 = num % (16*16) / 16; int i3 = num % (16*16*16 ...