python 中Dict 转 Json

来源:互联网 发布:信捷plc流程梯图编程 编辑:程序博客网 时间:2024/05/01 08:03

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


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

import jsonclass Student:      def __init__(self):          self.name = ''          self.age = 0class 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编码的中文正确显示

          

1 0