If you convert a dictionary to JSON, you're familiar with it, but what if you convert the class class to a JSON object at the advanced point?
1, first define a class
# define a student class class Student (object): def __init__ (Self,name,age,score): = name = age = Score
2, when instantiating the student class, pass in 3 parameters
# instantiate This object s = Student ('hello', 20,80)
3, use JSON transform s to instantiate the object to see if it succeeds
Print (Json.dumps (s))
4, Output: Direct reporting of TypeError type error, do not allow to directly convert the class to JSON
" C:\Python27\lib\json\encoder.py " inch default Raise " is not JSON serializable " <__main__is not 1
Solution:
1, define a conversion function
# define a conversion function to change the student class to a type acceptable to JSON def student2dict (STD): return { 'name': std.name, 'age' : std.age, 'score': Std.score }
2, in JSON print out
# This allows the class object to be converted to JSON, which uses the JSON default property to invoke the Student2dict function Print (Json.dumps (s,default=student2dict))
3, view the output so that the class object can be correctly transmitted through JSON
C:\Python27\python.exe e:/python/testspider/fibon.py{"age"" Score"" "name" "Hello"}
Python transforms a class object into JSON