Python-Json异常:Object of type Decimal is not JSON serializable
源起:
使用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的更多相关文章
- Object of type Decimal is not JSON serializable
json遇到Decimal 型数据无法正确处理 解决方案 import json result = [ {'name': '小红', 'age': 26, 'balance': decimal.Dec ...
- typeerror object of type ‘decimal‘ is not json serializable jsonify
当使用flask的jsonify返回json数据时,由于数据库有些字段类型使用decimal,而jsonify无法处理 解决方案 导入下面的包即可解决 pip install simplejson
- 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 ...
- Object of type 'ListSerializer' is not JSON serializable “listserializer”类型的对象不可JSON序列化
Object of type 'ListSerializer' is not JSON serializable “listserializer”类型的对象不可JSON序列化 一般原因为 序列化的对象 ...
- TypeError: Object of type 'int64' is not JSON serializable
错误类型:TypeError: Object of type 'int64' is not JSON serializable 错误场景:对Numpy和Pandas结果进行json.dumps报错 错 ...
- TypeError: Object of type 'int32' is not JSON serializable ——已解决
将模型用flask封装,返回json时报错:TypeError: Object of type 'int32' is not JSON serializable 网上搜索出的解决方案:重写json.J ...
- labelme2coco问题:TypeError: Object of type 'int64' is not JSON serializable
最近在做MaskRCNN 在自己的数据(labelme)转为COCOjson格式遇到问题:TypeError: Object of type 'int64' is not JSON serializa ...
- 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 ...
- TypeError: Object of type 'int32' is not JSON serializable
将模型用flask封装,返回json时报错:TypeError: Object of type 'int32' is not JSON serializable 网上搜索出的解决方案:重写json.J ...
- python 中的object与type的关系
object 和 type的关系很像鸡和蛋的关系,先有object还是先有type没法说,obejct和type是共生的关系,必须同时出现的. 在看下去之前,也要请先明白,在Python里面,所有的东 ...
随机推荐
- 【K哥爬虫普法】网盘用的好,“艳照门”跑不了
我国目前并未出台专门针对网络爬虫技术的法律规范,但在司法实践中,相关判决已屡见不鲜,K哥特设了"K哥爬虫普法"专栏,本栏目通过对真实案例的分析,旨在提高广大爬虫工程师的法律意识,知 ...
- bootstrap ----- bootstrap table表格参数
表格参数: 名称 标签 类型 默认 描述 - data-toggle String 'table' 不用写 JavaScript 直接启用表格. classes data-classes String ...
- 微信小程序-页面跳转Tabbar
官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#tabBar 首先我们 ...
- SpringCloud-07-Hystrix
Hystrix 熔断器 1.Hystrix 概述 Hystix 是 Netflix 开源的一个延迟和容错库,用于隔离访问远程服务.第三方库,防止出现级联失败(雪崩). 雪崩:一个服务失败,导致整条链路 ...
- [windows10]下Bad owner or permissions on .ssh/config的解决办法
按如下步骤操作即可: 进入如下路径C:\Users\用户名.ssh,你会看到有config这个文件 右击config,属性→安全→高级→禁止继承→删除所有继承→确定 如果系统是英文: Properti ...
- CH32V208蓝牙从机sleep模式下功耗测试
本测试基于CH32V208W的开发板:蓝牙从机模式:使用程序BLE_UART 在进行功耗测试的时候尽量去除额外耗电器件,将开发板上的VDD于VIO相连接,测功耗时直接给VDD供电. 将会对500ms, ...
- Delphi批量替换工具Cnpack
操,delphi官方 没有 批量替换工具,需要用到cnpack才可以,
- MySQL百万级数据大分页查询优化的实现
前言:在数据库开发过程中我们经常会使用分页,核心技术是使用用limit start, count分页语句进行数据的读取. 一.MySQL分页起点越大查询速度越慢 直接用limit start, cou ...
- DS12C887时钟模块, STC89和STC12的代码实现
DS12C887是时钟芯片DS12C885集成了电池和晶振的版本. 如果拆掉DS12C887的外壳, 能看到里面就是DS12C885. 功能特性 能输出世纪.年.月.日.时.分.秒等时间信息 集成电池 ...
- 【OpenGL ES】立方体手动旋转
1 前言 本文主要介绍使用 OpenGL ES 绘制立方体,并实现手动触摸事件控制立方体旋转. 为方便控制触摸旋转,假设旋转轴始终在 xoy 平面上,设 z 轴的方向向量 u = (0, 0, ...