Open In App

Convert class object to JSON in Python

Last Updated : 29 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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"}


Previous Article
Next Article

Similar Reads

Python | Ways to convert string to json object
In this article, we will see different ways to convert string to JSON in Python this process is called serialization. JSON module provides functions for encoding (serializing) Python objects into JSON strings and decoding (deserializing) JSON strings into Python objects. Encoding (Serializing) JSON: If you have a Python object and want to convert i
3 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
Convert HTML source code to JSON Object using Python
In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. We will use xmltojson mo
3 min read
Convert Generator Object To JSON In Python
JSON (JavaScript Object Notation) is a widely used data interchange format, and Python provides excellent support for working with JSON data. However, when it comes to converting generator objects to JSON, there are several methods to consider. In this article, we'll explore some commonly used methods. Convert Generator Object To JSON In PythonBelo
2 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
Deserialize JSON to Object in Python
Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module to perform this task : loads() : to deserialize a
2 min read
How to return a json object from a Python function?
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json and this module can be used to convert a python dictionary to JSON object. In Python dictionary is used to
2 min read
Python Json Serialize A Decimal Object
JSON (JavaScript Object Notation) is a widely used data interchange format due to its simplicity and readability. When working with Python, it's common to encounter situations where you must serialize Decimal objects to JSON. The decimal module in Python provides a way to handle decimal numbers with arbitrary precision. In this article, we'll explo
2 min read
Iterate Through Nested Json Object using Python
Working with nested JSON objects in Python can be a common task, especially when dealing with data from APIs or complex configurations. In this article, we'll explore some generally used methods to iterate through nested JSON objects using Python. Iterate Through Nested Json ObjectBelow, are the method of Iterate Through Nested JSON Object in Pytho
3 min read
Practice Tags :