Python复杂对象转json
Python复杂对象转json
python不常用, 出了岔子, 想将几个实体转成json, 但是因为实体列表里的实体里面套实体列表...直接使用json.dumps(obj)
会出现一些错误, 只能给里面的列表添加的时候调用object.__dict__
, 但是外层使用object.__dict__
就会报错, 很迷, 大概就是里面的元素无法序列化, 或者是某一个属性无法找到对应的"key".
嗐, 直接上代码:
# 其实这么写就可以了=.=
json.dumps(obj=self.students,
default=lambda x : x.__dict__, sort_keys=False, indent=2)
这里是一个小Demo:
import json
class Course:
def __init__(self, courseNum, courseName, courseCredit):
self.CourseNum = courseNum
self.CourseName = courseName
self.CourseCredit = courseCredit
class Student:
def __init__(self, studentNum, studentName, *courses):
self.StudentNum = studentNum
self.StudentName = studentName
self.Courses = []
self.Courses += courses
class IStudentResp(object):
def AddStudent(self, student):
pass
def SelectStudent(self, studentNum):
pass
def DeleteStudent(self, studentNum):
pass
def AddCourse(self, studentNum, course):
pass
def SelectCourse(self, studentNum, courseNum):
pass
def DeleteCourse(self, studentNum, courseNum):
pass
class StudentResp(IStudentResp):
students = []
def __init__(self):
pass
def AddStudent(self, student):
self.students.append(student)
def SelectStudent(self, studentNum):
for stu in self.students:
if studentNum == stu.StudentNum:
return stu
def DeleteStudent(self, studentNum):
self.students.remove(self.SelectStudent(studentNum))
def AddCourse(self, studentNum, course):
self.SelectStudent(studentNum).Courses.append(course)
def SelectCourse(self, studentNum, courseNum):
for stu in self.students:
if stu.StudentNum == studentNum:
for course in stu.Courses:
if course.CourseNum == courseNum:
return course
def DeleteCourse(self, studentNum, courseNum):
self.SelectStudent(studentNum).Courses\
.remove(self.SelectCourse(studentNum, courseNum))
def show(self):
print(json.dumps(obj=self.students,
default=lambda x : x.__dict__, sort_keys=False, indent=2))
# print(json.dumps(self.students))
if __name__ == "__main__":
sp = StudentResp()
sp.AddStudent(Student("001", "001", Course("A", "A", 2), Course("A", "A", 2)))
sp.AddStudent(Student("002", "001", Course("A", "A", 2), Course("A", "A", 2)))
sp.AddStudent(Student("003", "001", Course("A", "A", 2), Course("A", "A", 2)))
sp.AddStudent(Student("004", "001", Course("A", "A", 2), Course("A", "A", 2)))
sp.AddCourse("001", Course("A", "A", 2))
sp.AddCourse("001", Course("A", "A", 2))
sp.AddCourse("001", Course("A", "A", 2))
sp.AddCourse("001", Course("A", "A", 2))
sp.show()