Python - Convert 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 the json.dumps()
method.
In this tutorial, we will learn how to construct a JSON string from a Python class object using json.dumps()
and some common use cases.
Syntax of json.dumps()
Following is the syntax of the json.dumps()
function.
jsonStr = json.dumps(myobject.__dict__)
where
- json is the module.
- dumps is the method that converts the Python object to a 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 define a simple Python class, Laptop
, create an object of this 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)
Explanation:
- The class
Laptop
has two attributes:name
andprocessor
. - We create an object of the
Laptop
class calledlaptop1
, and assign it specific values for the attributes. - By using
json.dumps(laptop1.__dict__)
, we convert the object's attributes into a dictionary, which is then converted to a JSON string. - The resulting output is a JSON string representation of the object's attributes.
Output
{"name": "Dell Alienware", "processor": "Intel Core i7"}
2. Convert Class Object with Multiple Data Types to JSON
Here, we define a Python class with various data types (string, int, float), create an object of this class, and then convert it 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)
Explanation:
- The
Laptop
class is initialized with multiple data types:name
(string),processor
(string),hdd
(int),ram
(int), andcost
(float). - We create an object
laptop1
with these values and then convert the object’s attributes to a JSON string usingjson.dumps(laptop1.__dict__)
. - The method converts the class object into a JSON string, where the attributes are converted into JSON key-value pairs.
Output
{"name": "Dell Alienware", "processor": "Intel Core i7", "hdd": 512, "ram": 8, "cost": 2500.0}
3. Convert Class Object with Nested Object to JSON
In this example, we will show how to convert a class object containing another class object as an attribute into a JSON string.
Python Program
import json
class Processor:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
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 a nested object for processor
processor = Processor('Intel', '3.5 GHz')
# Create a Laptop object
laptop1 = Laptop('Dell Alienware', processor, 512, 8, 2500.00)
# Convert to JSON string
jsonStr = json.dumps(laptop1.__dict__, default=lambda o: o.__dict__)
# Print JSON string
print(jsonStr)
Explanation:
- The
Laptop
class now contains an instance of theProcessor
class as its attribute. - To convert this nested object to JSON, we use the
default=lambda o: o.__dict__
argument in thejson.dumps()
method. This tells Python how to handle custom objects likeProcessor
. - This method recursively converts the nested object to a dictionary before converting it to JSON.
Output
{"name": "Dell Alienware", "processor": {"brand": "Intel", "speed": "3.5 GHz"}, "hdd": 512, "ram": 8, "cost": 2500.0}
Summary
In this tutorial, we learned how to convert a Python Class Object to a JSON String using json.dumps()
. We explored examples for simple class objects, class objects with various data types, and even class objects with nested objects. These methods help in converting Python objects into a JSON-compatible format that can be easily saved or transmitted.