Converting Python objects to JSON can be beneficial in data sharing between systems that do not have an inherent Python language. A lot of programming languages can read and write JSON. This makes it a good choice for the data interchange.

What is JSON?

  • JSON (JavaScript Object Notation) is a text-based format to transfer and store data. The data is stored in a way it is easily readable by a human. 
  • Python language supports the built-in package “json”. The JSON package is imported when it is used. 
  • The JSON text has a string format and it contains key-value pairs enclosed in curly braces {}. This is what a dictionary looks like in Python.

How to Convert Python Class Object to JSON?

In Python, json.dumps() method is used to convert the Python class objects to the JSON format. The dumps method is needed when the result required is a string. Dump is essential for data storage purposes.

Syntax

res_var = json.dumps(object.__dict__)
  • “res_var” is the name of the variable
  • “json” is the name of the module that is imported
  • “dumps” is the method that will do the conversion
  • “object” defines the Python class object
  • “__dict__” is the dictionary format that the Python class object gets

Example 

Let us look at the given example to see how json.dumps() function can convert the Python class object to JSON format:

import json
class BandMember:
    def __init__(self, name, role):
        self.name = name
        self.role = role
bandMember_obj = BandMember("Adam", 'lead vocalist')
bandMember_json = json.dumps(bandMember_obj.__dict__)
print(bandMember_json)

In the above code,

  • The json module is imported so that it can be utilized in the Python language
  • A class “BandMember” is defined
  •  __init__ function is defined having the attributes self, name, and role
  • An instance of Bandmember “bandMember_obj” is created with the name “Adam” and the role “lead vocalist”.
  • json.dumps() function converts the Python class object “bandMember_obj” to the JSON format. The object’s attributes are converted into a dictionary using the “__dict__” attribute. The converted object is stored in the variable “bandMember_json”
  • print(bandMember_json) prints the JSON representation of the given object.

Output:

Conclusion

The Python class object can be converted to JSON format using json.dumps() method enabling you to dump the class object to JSON. This is a convenient and flexible method. The conversion between JSON and Python objects is an essential skill for programmers working on web APIS or an outside data source. This eases out the working with the other languages. To sum up, we discussed how we can convert a Python class object to a JSON format