Build a Json Object in Python
Last Updated :
23 Feb, 2024
JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for data exchange between a server and a web application, as well as between different components of a system. In Python, working with JSON is straightforward, and the built-in json
module provides functions to encode and decode JSON data. In this article, we’ll explore how to create and build JSON objects in Python.
Build a JSON Object in Python
Below are some of the ways by which we can build a JSON object in Python:
- Using Python Dictionary
- Using json.loads( )
- Using json.JSONEncoder
Build a JSON Object Using Python Dictionary
JSON module is imported to deal with JSON objects. A Python dictionary named ‘data’ is used to store the object in key-value pairs. json.dumps( ) is used convert the Python dictionary into JSON formatted string and result is displayed.
Python3
import json
data = {
"name" : "Guru" ,
"age" : 19 ,
"isStudent" : True
}
json_string = json.dumps(data)
print ( type (json_string))
print (json_string)
|
Output
<class 'str'>
{"name": "Guru", "age": 19, "isStudent": true}
Build a JSON Object Using json.loads( ):
In this example, the json.loads()
function is used to parse a JSON-formatted string json_string
into a Python dictionary named data
. The resulting dictionary is then printed, representing the decoded JSON data.
Python3
import json
json_string = '{"name": "GFG", "age": 19, "isStudent": true}'
data = json.loads(json_string)
print ( type (json_string))
print (data)
|
Output
<class 'str'>
{'name': 'GFG', 'age': 19, 'isStudent': True}
Build a JSON Object Using json.JSONEncoder:
Encoder function is defined that’s used for encoding sets and converting to list. A json object named ‘gfg’ is created as a set. This list is converted into a dictionary named ‘json_data’. The dictionary is converted into o a JSON string json_string using json.dumps() with the custom encoder ‘Encoder’.
Python3
import json
def encoder(obj):
if isinstance (obj, set ):
return list (obj)
return obj
gfg = [( 'name' , 'Hustlers' ), ( 'age' , 19 ), ( 'is_student' , True )]
json_data = dict (gfg)
json_string = json.dumps(json_data, default = encoder)
print ( type (json_string))
print (json_string)
|
Output
<class 'str'>
{"name": "Hustlers", "age": 19, "is_student": true}
Share your thoughts in the comments
Please Login to comment...