Friday, November 15, 2024
Google search engine
HomeLanguagesjson.loads() in Python

json.loads() in Python

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is used to store and exchange data. It is a language-independent format and is very easy to understand since it is self-describing in nature. There is a built-in package in Python that supports JSON data which is called as json module. The data in JSON is represented as quoted strings consisting of key-value mapping enclosed between curly brackets { }.

What are JSON loads () in Python?

The json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary.

Syntax : json.loads(s)

Argument: It takes a string, bytes, or byte array instance which contains the JSON document as a parameter (s).

Return: It returns a Python object.

Python json.loads() method

JSON Parsing using json.load() in Python

Suppose we have a JSON string stored in variable ‘x’ that looks like this.

x = """{
    "Name": "Jennifer Smith",
    "Contact Number": 7867567898,
    "Email": "jen123@gmail.com",
    "Hobbies":["Reading", "Sketching", "Horse Riding"]
    }"""

To parse the above JSON string firstly we have to import the JSON module which is an in-built module in Python. The string ‘x’ is parsed using json.loads() a method which returns a dictionary object as seen in the output.

Python3




import json
   
# JSON string:
# Multi-line string
x = """{
    "Name": "Jennifer Smith",
    "Contact Number": 7867567898,
    "Email": "jen123@gmail.com",
    "Hobbies":["Reading", "Sketching", "Horse Riding"]
    }"""
   
# parse x:
y = json.loads(x)
   
# Print the data stored in y
print(y)


Output

{'Name': 'Jennifer Smith', 'Contact Number': 7867567898, 'Email': 'jen123@gmail.com', 'Hobbies': ['Reading', 'Sketching', 'Horse Riding']}

Iterating over JSON Parsed Data using json.load() in Python

In the below code, after parsing JSON data using json.load() method in Python we have iterate over the keys in the dictionary and the print all key values pair using looping over the dictionary.

Python3




import json
     
# JSON string
employee ='{"id":"09", "name": "Nitin", "department":"Finance"}'
     
# Convert string to Python dict
employee_dict = json.loads(employee)
 
# Iterating over dictionary
for key in employee_dict:
  print(key," : ",employee_dict[key]);


Output

id  :  09
name  :  Nitin
department  :  Finance

Related Article: Pythonjson.load() in Python, Difference Between json.load() and json.loads()

RELATED ARTICLES

Most Popular

Recent Comments