The Wayback Machine - https://web.archive.org/web/20240807140316/https://www.geeksforgeeks.org/json-loads-in-python/
Open In App

json.loads() in Python

Last Updated : 20 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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.

Python
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.

Python
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: Python – json.load() in Python, Difference Between json.load() and json.loads()

json.loads() in Python – FAQs

What does JSON() do in Python?

json() is widely used to fetch data from APIs. Here’s what it does:

  • json.loads(): This function is used to parse (load) a JSON string and convert it into a Python dictionary (or list, depending on the JSON structure). It stands for “JSON load string”.
  • json.dumps(): This function is used to serialize (dump) a Python object (usually a dictionary or list) into a JSON formatted string. It stands for “JSON dump string”.

How to load a list of JSON in Python?

If you have a JSON array (list of JSON objects) stored as a string, you can use json.loads() to convert it into a Python list of dictionaries:

import json

# Example JSON array as a string
json_str = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]'

# Load JSON array into Python list of dictionaries
json_list = json.loads(json_str)

# Accessing elements in the list
for item in json_list:
print(item['name'], item['age'])

How to get JSON payload in Python?

If you’re working with web requests or APIs, the JSON payload (data) is typically received as part of the request. You can access it using libraries like requests for making HTTP requests:

import requests

# Example API endpoint
url = 'https://api.example.com/data'

# Making a GET request and accessing JSON payload
response = requests.get(url)
json_data = response.json() # Convert response JSON to Python object

# Process JSON data
print(json_data)

How can I customize the parsing of JSON objects using json.loads()?

You can customize the parsing of JSON objects in json.loads() by providing additional parameters:

  • object_hook: Allows you to specify a function that will be called to convert JSON objects to Python objects.
  • parse_float, parse_int, parse_constant: These parameters allow you to customize how numeric values are parsed.
  • object_pairs_hook: Allows you to specify a function that will be called to convert JSON object pairs into Python objects.

Here’s an example using object_hook:

import json

# Example JSON string with custom object keys
json_str = '{"name": "Alice", "age": 30}'

# Custom object hook function
def custom_object_hook(obj):
if 'age' in obj:
obj['age'] = int(obj['age']) # Convert age to integer if present
return obj

# Load JSON with custom object hook
data = json.loads(json_str, object_hook=custom_object_hook)

print(data)

Can I use json.loads() to parse JSON data from a file?

Yes, you can use json.loads() to parse JSON data from a file, but typically, you’d use json.load() for this purpose, which directly reads JSON data from a file object:

import json

# Example JSON file
file_path = 'data.json'

# Using json.load() to parse JSON data from file
with open(file_path, 'r') as file:
data = json.load(file)

# Process JSON data
print(data)
  • json.load(file): Reads JSON data from the specified file object and converts it into a Python object (dictionary or list).


    Similar Reads

    orjson.loads() vs json.loads() in Python
    orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
    4 min read
    Python - Difference Between json.load() and json.loads()
    JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
    3 min read
    Python orjson.loads() Method
    Python orjson.loads() method is used to deserialize a JSON string into a Python object using the orjson library of Python. In this article, we will learn about the Python orjson.loads() function. What is Python orjson.loads() Method?The orjson.loads() function is part of the orjson library and is used to deserialize JSON strings into Python objects
    2 min read
    Python - Difference between json.dump() and json.dumps()
    JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
    2 min read
    JSON Formatting in Python
    JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a lightweight data interchange format. It encodes Py
    3 min read
    Working With JSON Data in Python
    JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which cont
    6 min read
    Convert JSON to CSV in Python
    The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
    3 min read
    Reading and Writing JSON to a File in Python
    The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
    3 min read
    Read, Write and Parse JSON using Python
    JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON. Example of JSON String s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}
    4 min read
    Convert Text file to JSON in Python
    JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
    4 min read
    Article Tags :
    Practice Tags :
    three90RightbarBannerImg