Python transforms a class object into JSON

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.