json মডিউল ব্যবহার করে JSON ফাইল বা স্ট্রিং থেকে পাইথন ডিকশনারি তৈরি করা যায়।
ফাইল থেকে লোড
import json
with open('data.json') as f:
data = json.load(f)
# ডিকশনারি হিসেবে ব্যবহার
for k, v in data.items():
print(f"Key: {k}")
print(f"Value: {v}")
স্ট্রিং থেকে লোড
json_str = '{"name": "John", "age": 30}'
data = json.loads(json_str)
print(data['name']) # John
আউটপুট (ফাইল উদাহরণ)
Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, ...]}
সাধারণ প্যাটার্ন
import json
def load_json_file(filepath):
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
def save_json_file(data, filepath):
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)