Convert from Python object to JSON

By IncludeHelp Last updated : February 20, 2024

To convert from Python object to JSON, you can use the json.dumps() method by passing a Python object (dictionary). The json.dumps() method converts a Python object (i.e., dictionary) into a JSON string.

Program to convert from Python object to JSON

This example demonstrates converting from a Python object to a JSON string.

# Import the json module
import json

# Creating a Python object akka dictionary
student_dict = {"id": "101", "stdname": "ALex", "course": "MCA"}
# Printing value and type
print("student_dict :", student_dict)
print("Type of student_dict: ", type(student_dict))

# Converting Python object (dict) to JSON string
result = json.dumps(student_dict, indent=4)
print("After converting...")
print("result: ", result)
print("Type of result: ", type(result))

Output

The output of the above program is:

student_dict : {'id': '101', 'stdname': 'ALex', 'course': 'MCA'}
Type of student_dict:  <class 'dict'>
After converting...
result:  {
    "id": "101",
    "stdname": "ALex",
    "course": "MCA"
}
Type of result:  <class 'str'>

To understand the above program, you should have the basic knowledge of the following Python topics:

 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.