将实例对象编码成为json串的2种方式
Posted 未来可期
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将实例对象编码成为json串的2种方式相关的知识,希望对你有一定的参考价值。
import json
class Book():
def __init__(self,id,category,year,author):
self.id=id
self.category=category
self.year=year
self.author=author
class Book():
def __init__(self,id,category,year,author):
self.id=id
self.category=category
self.year=year
self.author=author
def print_sth(self):
print( "书的编号是%s类别是%s年代%s作者是%s"%(self.id,self.category,self.year,self.author))
def obj_detail(self,obj):
return {
"id":obj.id,
"category":obj.category,
"year":obj.year,
"author":obj.author
}
Book1=Book(1,2019,"prose","Tom")
js=json.dumps(Book1,default=Book1.obj_detail)
print(type(js))
print(js)
Book1.print_sth()
return {
"id":obj.id,
"category":obj.category,
"year":obj.year,
"author":obj.author
}
Book1=Book(1,2019,"prose","Tom")
js=json.dumps(Book1,default=Book1.obj_detail)
print(type(js))
print(js)
Book1.print_sth()
方式二
import json
class Book():
import json
class Book():
def __init__(self,id,category,year,author):
self.id=id
self.category=category
self.year=year
self.author=author
Book1=Book(1,2019,"prose","Tom")
js=json.dumps(Book1,default=lambda Book1:Book1.__dict__)
print(js)
print(type(js))
js=json.dumps(Book1,default=lambda Book1:Book1.__dict__)
print(js)
print(type(js))
以上是关于将实例对象编码成为json串的2种方式的主要内容,如果未能解决你的问题,请参考以下文章