json.loads() is a function from Python’s built-in json module that converts a JSON-formatted string into a corresponding Python object. It is mainly used when JSON data is received as text (for example, from APIs, files, or web responses) and needs to be processed in Python.
Example: This example shows how a JSON string is converted into a Python dictionary using json.loads().
import json
s = '{"language": "Python", "version": 3.11}'
d = json.loads(s)
print(d)
Output
{'language': 'Python', 'version': 3.11}
Explanation: json.loads(s) parses the JSON string s and converts it into a Python dict.
Syntax
json.loads(s)
- Parameters: s - A valid JSON string (can be of type str, bytes, or bytearray)
- Return Type: Returns a Python object such as dict, list, int, float, or str depending on the JSON content.
Examples
Example 1: This example converts a JSON string containing user details into a Python dictionary.
import json
s = '{"name": "Alex", "age": 25, "city": "Delhi"}'
d = json.loads(s)
print(d)
Output
{'name': 'Alex', 'age': 25, 'city': 'Delhi'}
Example 2: This example shows how a JSON array is converted into a Python list.
import json
s = '["Python", "Java", "C++"]'
lst = json.loads(s)
print(lst)
Output
['Python', 'Java', 'C++']
Explanation: json.loads(s) converts the JSON array into a Python list.
Example 3: This example demonstrates how parsed JSON data can be accessed like a normal Python dictionary.
import json
s = '{"id": 101, "role": "Developer"}'
d = json.loads(s)
print(d["role"])
Output
Developer
Explanation: After parsing, values are accessed using dictionary keys like d["role"].
Related Article: