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 of 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.

Examples

1. Convert 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 Code Copy

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.

2. Convert properties of 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 Code Copy

Output

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

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍