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里面,所有的东 ...
随机推荐
- vue写组件时的命名规范
1组件命名驼峰 如myBread.vue(组件) 2引入时,接受同样是驼峰 import MyBread from "@/components/cuscom/myBread.vue" ...
- hadoop实践01---hdfs分布式集群搭建与启动
一.hdfs集群组成结构
- 使用visio如何快速生成一个网格状图案,文档技巧!
如何使用visio如何快速生成一个网格状图案 我的成果图: 操作步骤如下: 1.新建一个visio文件,选择"基本框图".点击创建. 2.从左侧形状窗口中基本形状中选中正方形拖动到 ...
- 4.7 C++ Boost 多线程并发库
Boost 库是一个由C/C++语言的开发者创建并更新维护的开源类库,其提供了许多功能强大的程序库和工具,用于开发高质量.可移植.高效的C应用程序.Boost库可以作为标准C库的后备,通常被称为准标准 ...
- HanLP — 词性标注
词性(Part-Of-Speech,POS)指的是单词的语法分类,也称为词类.同一个类别的词语具有相似的语法性质 所有词性的集合称为词性标注集. 词性的用处 当下游应用遇到OOV时,可以通过OOV的词 ...
- 模式识别实验:基于主成分分析(PCA)的人脸识别
前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行了测试并输出特征脸,简单实现了人脸识别的功能. 1. 准备 ORL人脸数据集共包含40个不同人的400张图像,是在1992年4月至 ...
- 【奶奶看了也不会】AI绘画 Mac安装stable-diffusion-webui绘制AI妹子保姆级教程
1.作品图 2.准备工作 目前网上能搜到的stable-diffusion-webui的安装教程都是Window和Mac M1芯片的,而对于因特尔芯片的文章少之又少,这就导致我们还在用老Intel 芯 ...
- ASP.NET Core分布式项目实战(运行Consent Page)--学习笔记
任务21:运行Consent Page 修改 Config.cs 中的 RequireConsent 为 true,这样登录的时候就会跳转到 Consent 页面 修改 ConsentControll ...
- 从零开始的react入门教程(四),了解常用的条件渲染、列表渲染与独一无二的key
壹 ❀ 引 在从零开始的react入门教程(三),了解react事件与使用注意项一文中,我们了解了react中事件命名规则,绑定事件时对于this的处理,以及事件中可使用的e对象.那么这篇文章中我们来 ...
- java 从零开始手写 redis(十)缓存淘汰算法 LFU 最少使用频次
前言 java从零手写实现redis(一)如何实现固定大小的缓存? java从零手写实现redis(三)redis expire 过期原理 java从零手写实现redis(三)内存数据如何重启不丢失? ...