


Python json error xx is not JSON serializable solution introduction
This article mainly introduces the relevant information about the solution of Python json Error xx is not JSON serializable. Friends who need it can refer to it
Python json error xx is not JSON serializable solution
When using json, we often encounter xxx is not JSON serializable, that is, some cannot be serialized Object. Students who often use django know that django has its own Encoder to serialize commonly used objects such as time. In fact, we can define the serialization of specific types of objects ourselves. Let’s take a look at how to define and use it.
#!/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"} '''
The definition of the processing method is a subclass of inheritedjson.JSONEncoder, which is used in the clsfunction of the dumps methodAdd custom processing methods.
Thank you for reading, I hope it can help you, thank you for your support of this site!
The above is the detailed content of Python json error xx is not JSON serializable solution introduction. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...
