json.loads() in Python
JSON is a lightweight data format used for storing and exchanging data across systems. Python provides a built-in module called json to work with JSON data easily. The json.loads() method of JSON module is used to parse a valid JSON string and convert it into a Python dictionary. For example:
import json
s = '{"language": "Python", "version": 3.11}'
p = json.loads(s)
print(p)
Output
{'language': 'Python', 'version': 3.11}
Explanation:
- The data variable contains a JSON-formatted string.
- json.loads(s) parses the string and returns a Python dictionary.
- Now we can access values like p['language'] or p['version'].
In this article, we'll learn about the json.loads() method, how it works and practical examples to parse JSON strings into Python objects:
Syntax
json.loads(s)
Parameters:
- s: A valid JSON string (can be of type str, bytes, or bytearray)
Return Type: An Python object (typically a dict, but can also be a list, int, float, str, etc., based on the JSON structure)
Examples of json.loads() method
Example 1: Basic JSON Parsing
Let’s assume, we have a JSON string containing personal information. The below code demonstrates how to convert it to a Python dictionary.
import json
x = """{
"Name": "Prajjwal Vish",
"Contact Number": 1111111111,
"Email": "prajjwal@gmail.com",
"Hobbies": ["Reading", "Sketching", "Playing Chess"]
}"""
y = json.loads(x)
print(y)
Output
{'Name': 'Prajjwal Vish', 'Contact Number': 1111111111, 'Email': 'prajjwal@gmail.com', 'Hobbies': ['Reading', 'Sketching', 'Playing Chess']}
Explanation:
- The multi-line string x contains valid JSON.
- json.loads(x) converts it into a Python dictionary.
Example 2: Iterating Over Parsed Data
Once parsed, we can loop through the dictionary just like any other Python dict:
import json
e = '{"id": "09", "name": "Nitin", "department": "Finance"}'
e_dict = json.loads(e)
for key in e_dict:
print(key, ":", e_dict[key])
Output
id : 09 name : Nitin department : Finance
Explanation:
- The JSON string employee is converted to a Python dictionary.
- We then loop through each key and print its corresponding value.
Related Article: