python 中Dict 转 Json

近期在公司须要写个小工具。运用到的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编码的中文正确显示

          

posted @ 2017-04-27 20:26  zsychanpin  阅读(420)  评论(0编辑  收藏  举报