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.
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.
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 usejson.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).