Skip to content
Related Articles

Related Articles

Convert class object to JSON in Python

Improve Article
Save Article
  • Last Updated : 29 Dec, 2020
Improve Article
Save Article

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)

Parameter: Expects a dictionary object.

Return: json string

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

Python3




# import required packages
import json
  
# custom class
class Student:
    def __init__(self, roll_no, name, batch):
        self.roll_no = roll_no
        self.name = name
        self.batch = batch
  
  
class Car:
    def __init__(self, brand, name, batch):
        self.brand = brand
        self.name = 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
    print(jsonstr1)
    print(jsonstr2)
    print(jsonstr3)
    print(jsonstr4)

Output:

{"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
Related Articles

Start Your Coding Journey Now!