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

json.loads() in Python

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

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

    json.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
    Saving Text, JSON, and CSV to a File in Python
    Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
    5 min read
    Flattening JSON objects 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 module
    3 min read
    Pretty Print JSON in Python
    JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. 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 Read, Write and Parse JSON using Python Pretty Print JSON Whenever d
    2 min read
    Python - JSON to XML
    A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server.A JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSON
    5 min read
    Python - XML to JSON
    A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server. A JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSO
    4 min read
    How to import JSON File in MongoDB using Python?
    Prerequisites: MongoDB and Python, Working With JSON Data in Python MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. JSON stands for JavaScript Object Notation. It is an open standard file format, and data int
    2 min read
    Encoding and Decoding Custom Objects in Python-JSON
    JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it's the most widely used format for the REST APIs. Note: For
    5 min read
    How to Parse Data From JSON into Python?
    JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it. Before starting the det
    2 min read
    Convert JSON data Into a Custom Python Object
    Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
    2 min read
    Deserialize JSON to Object in Python
    Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module to perform this task : loads() : to deserialize a
    2 min read
    Convert multiple JSON files to CSV Python
    In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
    8 min read
    Python JSON
    Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects including parsing, serializing, deserializing, and
    3 min read
    Convert class object to JSON in Python
    Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
    2 min read
    How to return a json object from a Python function?
    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 and this module can be used to convert a python dictionary to JSON object. In Python dictionary is used to
    2 min read
    How to compare JSON objects regardless of order in Python?
    JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primaril
    2 min read
    How to read a JSON response from a link in Python?
    There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which he
    2 min read
    Convert HTML source code to JSON Object using Python
    In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. We will use xmltojson mo
    3 min read
    Extract JSON from HTML using BeautifulSoup in Python
    In this article, we are going to extract JSON from HTML using BeautifulSoup in Python. Module neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.pip install bs4requests: Request allows you to send HTTP/1
    3 min read
    How to communicate JSON data between Python and Node.js ?
    The following article covers how to communicate JSON data between Python and Node.js. Suppose we are working with the Node.js application, and we want to make use of a specific library that is only available in python or vice versa. We should be able to share the results from one language to another and to achieve it, we will use the JSON as it is
    7 min read
    Convert nested JSON to CSV in Python
    In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
    9 min read
    Article Tags :
    Practice Tags :