当前位置:Gxlcms > Python > Python自定义类对象序列化为Json串(代码示例)

Python自定义类对象序列化为Json串(代码示例)

时间:2021-07-01 10:21:17 帮助过:590人阅读

本篇文章给大家带来的内容是关于Python自定义类对象序列化为Json串(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

之前已经实现了Python: Json串反序列化为自定义类对象,这次来实现了Json的序列化。

测试代码和结果如下:

  1. import Json.JsonTool
  2. class Score:
  3. math = 0
  4. chinese = 0
  5. class Book:
  6. name = ''
  7. type = ''
  8. class Student:
  9. id = ''
  10. name = ''
  11. score = Score()
  12. books = [Book()]
  13. student = Student()
  14. json_data = '{"id":"123", "name":"kid", "score":{"math":100, "chinese":98}, ' \
  15. '"books":[{"name":"math", "type":"study"}, ' \
  16. '{"name":"The Little Prince", "type":"literature"}]} '
  17. Json.JsonTool.json_deserialize(json_data, student)
  18. print(student.name)
  19. print(student.score.math)
  20. print(student.books[1].name)
  21. student_str = Json.JsonTool.json_serialize(student)
  22. print(student_str)
  23. input("\n按回车键退出。")

运行结果:

  1. kid100The Little Prince
  2. {"books": [{"name": "math", "type": "study"}, {"name": "The Little Prince", "type": "literature"}], "id": "123", "name": "kid", "score": {"chinese": 98, "math": 100}}
  3. 按回车键退出。

实现代码如下:

  1. def json_serialize(obj):
  2. obj_dic = class2dic(obj)
  3. return json.dumps(obj_dic)
  4. def class2dic(obj):
  5. obj_dic = obj.__dict__
  6. for key in obj_dic.keys():
  7. value = obj_dic[key]
  8. obj_dic[key] = value2py_data(value)
  9. return obj_dic
  10. def value2py_data(value):
  11. if str(type(value)).__contains__('__main__'):
  12. # value 为自定义类
  13. value = class2dic(value)
  14. elif str(type(value)) == "<class 'list'>":
  15. # value 为列表
  16. for index in range(0, value.__len__()):
  17. value[index] = value2py_data(value[index])
  18. return value

以上就是Python自定义类对象序列化为Json串(代码示例)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行