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.
- Object is first converted into dictionary format using __dict__ attribute.
- 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 json
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
if __name__ = = "__main__" :
s1 = Student( "85" , "Swapnil" , "IMT" )
s2 = Student( "124" , "Akash" , "IMT" )
c1 = Car( "Honda" , "city" , "2005" )
c2 = Car( "Honda" , "Amaze" , "2011" )
jsonstr1 = json.dumps(s1.__dict__)
jsonstr2 = json.dumps(s2.__dict__)
jsonstr3 = json.dumps(c1.__dict__)
jsonstr4 = json.dumps(c2.__dict__)
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"}
Please Login to comment...