The json
package in Python lets us work with JavaScript Object Notation (JSON). We can also use it to convert any Python object into JSON data.
To do this, we need to import the json
package at the start of the program we want to write.
import json
There are two major use-cases of JSON in Python:
Let's see discuss both in detail.
The json.loads()
function converts or retrieves the components of the JSON string into the dictionary.
json.loads(str String)
In this example, we parse a JSON string into a Python dictionary.
import json# JSON stringmyjson = '{ "student name":"Fahad Sajid", "class":"Purple", "Distinction":"House Caption"}'# Parsing the JSON stringmydict = json.loads(myjson)print(mydict["Distinction"])print(mydict["class"])
json
package.myjson
. We use this name to access the string.json.loads(myjson)
function. This loads the JSON string in the Python dictionary, which is represented by mydict
.Distinction
value from mydict
. By using this function, we can filter any part of the string.class
using the same resolution operator ([]
).The json.dumps()
function converts any Python object into a JSON string.
json.dumps(Python_obj)
In this example, we convert a Python dictionary into a JSON format.
import json# Dictionary objectpython_obj = {"Student_name":"Michael Linda","Class":"Green","Marks":80,"Distinction":"Random"}# Invoking the json.dump() methodnewjson = json.dumps(python_obj)print(newjson)
json
package.python_obj
.json.dumps(python_obj)
function. This sends the ython object to the JSON string. newjson
represents the new JSON string we generate.