搜索
首页后端开发Python教程Python json 错误xx is not JSON serializable解决办法介绍

这篇文章主要介绍了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 
&#39;&#39;&#39; 
 
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 = {&#39;num&#39;:1112, &#39;date&#39;:datetime.now()} 
print json.dumps(json_1, cls=DateEncoder) 
 
&#39;&#39;&#39;&#39;&#39; 
输出结果: 
 
PS D:\code\python\python_abc> python .\json_extention.py 
{"date": "2014-03-16 13:56:39.003000", "num": 1112} 
&#39;&#39;&#39; 
 
#我们自定义一个类试试 
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 = {&#39;user&#39;:User(&#39;orangle&#39;)} 
print json.dumps(json_2, cls=UserEncoder) 
 
&#39;&#39;&#39;&#39;&#39; 
PS D:\code\python\python_abc> python .\json_extention.py 
{"date": "2014-03-16 14:01:46.738000", "num": 1112} 
{"user": "orangle"} 
 
&#39;&#39;&#39;

定义处理方法是继承json.JSONEncoder的一个子类,使用的时候是在dumps方法的cls函数中添加自定义的处理方法。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

以上是Python json 错误xx is not JSON serializable解决办法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

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

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

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

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

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

阵列的同质性质如何影响性能?阵列的同质性质如何影响性能?Apr 25, 2025 am 12:13 AM

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

编写可执行python脚本的最佳实践是什么?编写可执行python脚本的最佳实践是什么?Apr 25, 2025 am 12:11 AM

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

Numpy数组与使用数组模块创建的数组有何不同?Numpy数组与使用数组模块创建的数组有何不同?Apr 24, 2025 pm 03:53 PM

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

Numpy数组的使用与使用Python中的数组模块阵列相比如何?Numpy数组的使用与使用Python中的数组模块阵列相比如何?Apr 24, 2025 pm 03:49 PM

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

CTYPES模块与Python中的数组有何关系?CTYPES模块与Python中的数组有何关系?Apr 24, 2025 pm 03:45 PM

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

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

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

热工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

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

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。