json.loads(): parses a JSON-formatted string and returns it as a Python dictionary, list, or others

By using json.loads() we can decode Json formatted data to Python object

In our example codes below we will check each object type after converting from Json to Python object.

Getting Boolean type
import json
my_str='true'
print(json.loads(my_str)) # True
print(type(json.loads(my_str))) # <class 'bool'>
Getting None type
import json
my_str='null'
print(json.loads(my_str)) # None
print(type(json.loads(my_str))) # <class 'NoneType'>
Getting a List
import json
my_str='["First","Second","Third"]'
print(json.loads(my_str)) # ['First', 'Second', 'Third']
print(type(json.loads(my_str))) # <class 'list'>
Getting a Dictionary
import json
my_str='{"id":"2","name":"Max Ruin","class1":"Three5","mark":"85"}'
print(json.loads(my_str)) # {'id': '2', 'name': 'Max Ruin', 'class1': 'Three5', 'mark': '85'}
print(type(json.loads(my_str))) # <class 'dict'>

Example 1: Decoding Nested JSON Data

import json
nested_json = '{"name": "John", "details": {"age": 30, "city": "New York"}}'
output = json.loads(nested_json)
print(output)  # Output: {'name': 'John', 'details': {'age': 30, 'city': 'New York'}}
Output:
{'name': 'John', 'details': {'age': 30, 'city': 'New York'}}

Example 2: Decoding JSON Array

import json
json_array = '[10, 20, 30, 40]'
output = json.loads(json_array)
print(output)  # Output: [10, 20, 30, 40]
Output:
[10, 20, 30, 40]

Example 3: Handling Malformed JSON Data

import json
malformed_json = '{"name": "John", "age": 30,'  # Missing closing bracket
try:
    output = json.loads(malformed_json)
except json.JSONDecodeError as e:
    print(f"Error: {e}")  # Output: Error message indicating malformed JSON
Output:
Error: Expecting property name enclosed in double quotes

Example 4: Decoding JSON with Boolean Values

import json
json_data = '{"is_active": true, "is_verified": false}'
output = json.loads(json_data)
print(output)
Output:
{'is_active': True, 'is_verified': False}
load() to read Json data from file
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer