Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Convert class object to JSON in Python

  • Last Updated : 29 Dec, 2020

Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object’s attributes. 

  1. Object is first converted into dictionary format using __dict__ attribute.
  2. This newly created dictionary is passed as a parameter to json.dumps() which then yields a JSON string.

Syntax: json.dumps(Object obj)

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Parameter: Expects a dictionary object.

Return: json string

Following python code converts a python class Student object to JSON.


# import required packages
import json
# custom class
class Student:
    def __init__(self, roll_no, name, batch):
        self.roll_no = roll_no = name
        self.batch = batch
class Car:
    def __init__(self, brand, name, batch):
        self.brand = brand = name
        self.batch = batch
# main function
if __name__ == "__main__":
    # create two new student objects
    s1 = Student("85", "Swapnil", "IMT")
    s2 = Student("124", "Akash", "IMT")
    # create two new car objects
    c1 = Car("Honda", "city", "2005")
    c2 = Car("Honda", "Amaze", "2011")
    # convert to JSON format
    jsonstr1 = json.dumps(s1.__dict__)
    jsonstr2 = json.dumps(s2.__dict__)
    jsonstr3 = json.dumps(c1.__dict__)
    jsonstr4 = json.dumps(c2.__dict__)
    # print created JSON objects


{"roll_no": "85", "name": "Swapnil", "batch": "IMT"}
{"roll_no": "124", "name": "Akash", "batch": "IMT"}
{"brand": "Honda", "name": "city", "batch": "2005"}
{"brand": "Honda", "name": "Amaze", "batch": "2011"}

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!