本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于Python自定义类对象序列化为Json串(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
之前已经实现了Python: Json串反序列化为自定义类对象,这次来实现了Json的序列化。
测试代码和结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import Json.JsonTool
class Score:
math = 0
chinese = 0
class Book:
name = ''
type = ''
class Student:
id = ''
name = ''
score = Score()
books = [Book()]
student = Student()
json_data = '{"id":"123", "name":"kid", "score":{"math":100, "chinese":98}, ' \
'"books":[{"name":"math", "type":"study"}, ' \
'{"name":"The Little Prince", "type":"literature"}]} '
Json.JsonTool.json_deserialize(json_data, student)
print (student.name)
print (student.score.math)
print (student.books[1].name)
student_str = Json.JsonTool.json_serialize(student)
print (student_str)
input( "\n按回车键退出。" )
|
运行结果:
1 2 3 4 | kid100The Little Prince
{ "books" : [{ "name" : "math" , "type" : "study" }, { "name" : "The Little Prince" , "type" : "literature" }], "id" : "123" , "name" : "kid" , "score" : { "chinese" : 98, "math" : 100}}
按回车键退出。
|
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | def json_serialize(obj):
obj_dic = class2dic(obj)
return json.dumps(obj_dic)
def class2dic(obj):
obj_dic = obj.__dict__
for key in obj_dic.keys():
value = obj_dic[key]
obj_dic[key] = value2py_data(value)
return obj_dic
def value2py_data(value):
if str(type(value)).__contains__( '__main__' ):
# value 为自定义类
value = class2dic(value)
elif str(type(value)) == "<class 'list'>" :
# value 为列表
for index in range(0, value.__len__()):
value[index] = value2py_data(value[index])
return value
|
以上就是Python自定义类对象序列化为Json串(代码示例)的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python是面向对象吗
Python怎么看数据类型
Python输出hello world代码的方法
pycharm怎么用Python
Python如何合并两个列表
Python怎么把三位数拆开
Python里lambda是什么
在Python中面向对象该如何编程
解析实例讲解什么是Python random模块
Python中二叉堆的详细介绍(代码示例)
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python自定义类对象序列化为Json串(代码示例)