Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

json.loads() in Python

  • Last Updated : 22 Jun, 2020

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. The data in JSON is represented as quoted-strings consisting of key-value mapping enclosed between curly brackets {}.

json.loads()

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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.

Example 1:Suppose the JSON string looks like this.

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

In order to read the content of this string following implementation needs to be carried out:




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)
  
# the result is a Python dictionary:
print(y)

Output:

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

Here, the string x is parsed using json.loads() method which returns a dictionary.

Example 2:




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

Output:

{'id': '09', 'department': 'Finance', 'name': 'Nitin'}
Nitin



My Personal Notes arrow_drop_up