Summary: In this tutorial, we will learn how to convert an object into JSON and viceversa in Python.
Convert Python Object to JSON
The json.dumps()
method of the json
module converts a dictionary into a JSON string.
json inspired by JavaScript is a Python inbuilt module used to work with JSON data.
Syntax:
json_string = json.dumps(<dictionary_object>)
We can use the json.dumps()
method to convert an object in Python into JSON. All we need to do is to pass the dictionary representation of the object as a parameter to this method.
where object.__dict__
is the dictionary representation of Python object.
Example:
import json
class Student:
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
#object
student_obj = Student("Pencil Programmer", 7)
#JSON
student_json = json.dumps(student_obj.__dict__)
print(student_json)
Output:
{“name”: “Pencil Programmer”, “roll_no”: 7}
Convert JSON to Python Object
The json.loads()
method of json
module converts a JSON string into a Python dictionary (opposite of json.dumps()
).
Syntax:
object_dict= json.loads(json_string)
We can use the dictionary returned by the json.loads()
method as keywords arguments (**kwargs) to construct an object of a given Python class.
Example:
import json
class Student:
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
#JSON
student_json = '{"name": "Pencil Programmer", "roll_no": 7}'
#dictionary
student_dict = json.loads(student_json)
#object
student_obj = Student(**student_dict)
print("Name: ", student_obj.name)
print("Roll: ", student_obj.roll_no)
Output:
Name: Pencil Programmer
Roll: 7
It is important to note that, json.load()
and json.loads()
are two different methods.
- json.load() reads JSON encoded data and convert it into a Python dictionary.
- json.loads() parse JSON string into Python dictionary.