这篇文章主要介绍了Python json 错误xx is not JSON serializable解决办法的相关资料,需要的朋友可以参考下
Python json 错误xx is not JSON serializable解决办法
在使用json的时候经常会遇到xxx is not JSON serializable,也就是无法序列化某些对象。经常使用django的同学知道django里面有个自带的Encoder来序列化时间等常用的对象。其实我们可以自己定定义对特定类型的对象的序列化,下面看下怎么定义和使用的。
#!/usr/bin/env python # -*- coding: utf-8 -*- #json_extention #2014-03-16 #copyright: orangleliu #license: BSD ''''' python中dumps方法很好用,可以直接把我们的dict直接序列化为json对象 但是有的时候我们加了一些自定义的类就没法序列化了,这个时候需要 自定义一些序列化方法 参考: http://www.php.cn/ 例如: In [3]: from datetime import datetime In [4]: json_1 = {'num':1112, 'date':datetime.now()} In [5]: import json In [6]: json.dumps(json_1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) D:\devsofts\python2.7\lib\site-packages\django\core\management\commands\shell.py c in <module>() ----> 1 json.dumps(json_1) TypeError: datetime.datetime(2014, 3, 16, 13, 47, 37, 353000) is not JSON serial izable ''' from datetime import datetime import json class DateEncoder(json.JSONEncoder ): def default(self, obj): if isinstance(obj, datetime): return obj.str() return json.JSONEncoder.default(self, obj) json_1 = {'num':1112, 'date':datetime.now()} print json.dumps(json_1, cls=DateEncoder) ''''' 输出结果: PS D:\code\python\python_abc> python .\json_extention.py {"date": "2014-03-16 13:56:39.003000", "num": 1112} ''' #我们自定义一个类试试 class User(object): def init(self, name): self.name = name class UserEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, User): return obj.name return json.JSONEncoder.default(self, obj) json_2 = {'user':User('orangle')} print json.dumps(json_2, cls=UserEncoder) ''''' PS D:\code\python\python_abc> python .\json_extention.py {"date": "2014-03-16 14:01:46.738000", "num": 1112} {"user": "orangle"} '''
定义处理方法是继承json.JSONEncoder的一个子类,使用的时候是在dumps方法的cls函数中添加自定义的处理方法。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
以上是Python json 错误xx is not JSON serializable解决办法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。