We can easily convert any Python class object to JSON format using json.dumps() method.

Syntax:

json_string = json.dumps(object.__dict__)

where object.__dict__ is the dictionary representation of Python object.

json inspired by javascript is a Python inbuilt module used to work with JSON data.

Example: Convert Python Class Object to JSON

Let’s convert a python object into JSON in code.

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}

json.dumps() accept python dictionary as an argument, so we pass the dictionary representation of the object using its __dict__ attribute.

Example: Convert JSON String to Python Object

We can easily convert a JSON string into python object using json.loads() method and python varargs.

Syntax:

object_dict= json.loads(json_string)

json.loads() return dictionay form of JSON String, which we can use it to construct python object.

Let’s see an example of converting JSON string to Python object in code.

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

Remember, json.load() and json.loads() are two different method.

  • json.load() read JSON encoded data and convert it into Python dictionary.
  • json.loads() parse JSON string into Python dictionary.

If you have any doubts or suggestion then please comment below.

Leave a Reply

5 + 15 =