python 中Dict 转 Json

2023-05-16

最近在公司需要写个小工具,运用到的python,然后需要将Dict转成Json。之前遇到转换Json失败,然后以为复杂的Entity结构,不能用Json的库Json.dump(),进行转换。自己些了一个转换函数,但是效果还是不理想,后来经过大牛点拨,说Dict都可以转换成Json。


为了防止以后踩坑,废话不多说,直接上代码:

import json

class Student:
      def __init__(self):
          self.name = ''
          self.age = 0

class Course:
      def __init__(self):
          self.name = ''
          self.student_list = []

class Parser:
      def __init__(self):
          self.course = Course()

      def parse():
          student = Student()
          student.name = 'Jack'
          student.age = 28

          student2 = Student()
          student.name = 'Lily'
          student.age = 30

          course = Course()
          course.name = 'History'
          course.student_list.append(student.__dict___) // 这里注意,不应该写成course.student_list.append(student)
          course.student_list.append(student2.__dict__)  

          print json.dump(course.__dict__, ensure_ascii = False) // ensure_ascii=False, 是将utf-8编码的中文正确显示

          

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 中Dict 转 Json 的相关文章

随机推荐