How to Convert Python Class Object to JSON?

Python – Convert Class Object to JSON

To convert a Python Class Object to JSON String, or save the parameters of the class object to a JSON String, use json.dumps() method.

In this tutorial, we will learn how to construct a JSON string from a Python class object.

Syntax – json.dumps()

Following is the syntax of json.dumps() function.

jsonStr = json.dumps(myobject.__dict__)

where

  • json is the module.
  • dumps is the method that converts the python object to JSON string. It returns a JSON string.
  • myobject is the Python Class object and myobject.__dict__ gets the dictionary version of object parameters.

Example 1: Convert Python Class Object to JSON string

In this example, we will define a Python class, create an object for the python class, and then convert its properties to a JSON string.

Python Program

import json

class Laptop:
	name = 'My Laptop'
	processor = 'Intel Core'
		
#create object
laptop1 = Laptop()
laptop1.name = 'Dell Alienware'
laptop1.processor = 'Intel Core i7'

#convert to JSON string
jsonStr = json.dumps(laptop1.__dict__)

#print json string
print(jsonStr)
Run this program ONLINE

Output

{"name": "Dell Alienware", "processor": "Intel Core i7"}

The property names are converted to JSON keys while the their values are converted to JSON values.

Example 2: Convert Properties of Python Class Object to JSON string

In the following example, we will define a Python class with different datatypes like string, int and float; create an object for the python class, and then convert the Python Class Object properties to a JSON string.

Python Program

import json

class Laptop:
	def __init__(self, name, processor, hdd, ram, cost):
		self.name = name
		self.processor = processor
		self.hdd = hdd
		self.ram = ram
		self.cost = cost
		
#create object
laptop1 = Laptop('Dell Alienware', 'Intel Core i7', 512, 8, 2500.00)

#convert to JSON string
jsonStr = json.dumps(laptop1.__dict__)

#print json string
print(jsonStr)
Run this program ONLINE

Output

{"name": "Dell Alienware", "processor": "Intel Core i7", "hdd": 512, "ram": 8, "cost": 2500.0}

Summary

In this tutorial of Python Examples, we learned to convert a Python Class Object to JSON String with the help of Python Examples.