json序列化常见异常处理
json序列化异常TypeError: Object of type xxx is not JSON serializable
json序列化时,只支持基本类型,bool,None,数值,字符串,tuple,dict(对应定义JSONObject),一般不支持具体编程语言的类对象
book = {
"1" : True,
"2" : None,
"3" : "A" ,
"4" : tuple ( ) ,
"5" : tuple ( [ 1 , 2 ] ) ,
"6" : dict ( ) ,
}
print ( json. dumps ( book) )
# { "1" : true , "2" : null , "3" : "A" , "4" : [ ] , "5" : [ 1 , 2 ] , "6" : { } }
class BookClass :
def __init__ ( self) :
self. name = ""
self. author = ""
self. price = 0.0
book = BookClass ( )
print ( json. dumps ( book) )
# TypeError: Object of type BookClass is not JSON serializable
python没有定义类似__json__魔术方法,要序列化类对象,首先主动转化为基本类型,或者定制json库行为
class BookClass :
. . .
def to_json ( self) :
return {
"name" : self. name,
"author" : self. author,
"price" : self. price,
}
book = BookClass( )
print ( json. dumps( book. to_json( ) ) )
def _json_hook ( self, obj) :
return getattr ( obj, "to_json" , _json_default) ( )
_json_default = json. JSONEncoder. default
json. JSONEncoder. default = _json_hook
book = BookClass( )
print ( json. dumps( book) )
json序列化异常ValueError: Circular reference detected
json序列化时不能循环引用,json定义没有对象引用类型 循环引用语法层面是没有任何问题的,可以用print打印查看
import json
publisher = { "name" : "IT民工" , "books" : [ ] }
book_a = { }
book_a[ "name" ] = "码农的世界"
book_a[ "author" ] = "码农a"
book_a[ "price" ] = 5.55
book_a[ "publisher" ] = publisher
book_b = { }
book_b[ "name" ] = "码农的逆袭"
book_b[ "author" ] = "1024"
book_b[ "price" ] = 555
book_b[ "publisher" ] = publisher
print ( json. dumps( book_a) )
print ( publisher)
print ( json. dumps( publisher) )
publisher[ "books" ] . append( book_a)
publisher[ "books" ] . append( book_b)
print ( publisher)
print ( json. dumps( publisher) )