JSON String को Dictionary में Convert करना
JSON String को Dictionary में Convert करने के लिए json.loads() का उपयोग करें। यह Method Valid JSON String Accept करता है और Dictionary Return करता है जिसमें आप सभी Elements Access कर सकते हैं।
उदाहरण
>>> import json
>>> s = '{"success": "true", "status": 200, "message": "Hello"}'
>>> d = json.loads(s)
>>> print(d["success"], d["status"])
true 200
JSON File से Directly Load करना:
यदि आपके पास JSON File है और उससे Dict Construct करना चाहते हैं, तो json.load() Method का उपयोग करें।
import json
with open('data.json', 'r') as f:
data = json.load(f)
print(data['success'])
Complete Example with Error Handling:
import json
def parse_json_string(json_string):
"""Safely Parse JSON String"""
try:
return json.loads(json_string)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
return None
# Test
valid_json = '{"name": "Alice", "age": 30}'
invalid_json = '{"name": "Alice", "age": 30' # Missing }
print(parse_json_string(valid_json)) # {'name': 'Alice', 'age': 30}
print(parse_json_string(invalid_json)) # None + Error Message
Python Objects को JSON String में Convert करना:
import json
data = {'name': 'Alice', 'age': 30, 'active': True}
# Compact
json_string = json.dumps(data)
# '{"name": "Alice", "age": 30, "active": true}'
# Pretty
json_string = json.dumps(data, indent=2)
# {
# "name": "Alice",
# "age": 30,
# "active": true
# }