SoFunction
Updated on 2025-03-02

Python json error xx is not JSON serializable solution

Python json error xx is not JSON serializable solution

I often encounter it when using jsonxxx  is not JSON serializable, that is, it is impossible to serialize certain objects. Students who often use django know that django has a built-in Encoder to serialize commonly used objects such as time. In fact, we can define the serialization of specific types of objects by ourselves. Let’s see how to define and use them.

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
#json_extention 
#2014-03-16 
#copyright: orangleliu 
#license: BSD 
 
''''' 
pythonmiddledumpsThe method is very useful,Can directly put oursdictDirectly serialize tojsonObject 
But sometimes we can't serialize it after adding some custom classes.,This time it is necessary 
Customize some serialization methods 
 
refer to: 
/2.7/library/ 
 
For example: 
In [3]: from datetime import datetime 
 
In [4]: json_1 = {'num':1112, 'date':()} 
 
In [5]: import json 
 
In [6]: (json_1) 
--------------------------------------------------------------------------- 
TypeError                 Traceback (most recent call last) 
D:\devsofts\python2.7\lib\site-packages\django\core\management\commands\ 
c in <module>() 
----> 1 (json_1) 
 
TypeError: (2014, 3, 16, 13, 47, 37, 353000) is not JSON serial 
izable 
''' 
 
from datetime import datetime 
import json 
 
class DateEncoder( ): 
  def default(self, obj): 
    if isinstance(obj, datetime): 
      return obj.__str__() 
    return (self, obj) 
 
json_1 = {'num':1112, 'date':()} 
print (json_1, cls=DateEncoder) 
 
'''''
 Output result:
 
 PS D:\code\python\python_abc> python .\json_extention.py
 {"date": "2014-03-16 13:56:39.003000", "num": 1112}
 ''' 
 
#Let's try customizing a classclass User(object): 
  def __init__(self, name): 
     = name 
 
class UserEncoder(): 
  def default(self, obj): 
    if isinstance(obj, User): 
      return  
    return (self, obj) 
 
json_2 = {'user':User('orangle')} 
print (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"} 
 
''' 

Defining a processing method is an inherited subclass. When used, you add a custom processing method to the cls function of the dumps method.

Thank you for reading, I hope it can help you. Thank you for your support for this site!