码迷,mamicode.com
首页 > 编程语言 > 详细

python 中Dict 转 Json

时间:2017-04-27 21:04:13      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:false   工具   pre   self   小工具   history   理想   lis   自己   

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

          

python 中Dict 转 Json

标签:false   工具   pre   self   小工具   history   理想   lis   自己   

原文地址:http://www.cnblogs.com/zsychanpin/p/6776375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!