๐ JSON Handling
JSON is a lightweight data interchange format inspired by JavaScript object literal syntax.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import json from datetime import datetime from pathlib import Path from decimal import Decimal # 1. Serialize / deserialize basics user_data = { "id" : "pyn-001", "username": "santoshtvk", "premium" : True, "score" : 95.5, "courses" : ["Python", "AI"], "joined" : "2024-01-15", } json_str = json.dumps(user_data, indent=2, sort_keys=True) print("Serialized:\n", json_str) restored = json.loads(json_str) print("\nRestored username:", restored["username"]) # 2. Read / write JSON files data_path = Path("pynfinity_users.json") with open(data_path, "w", encoding="utf-8") as f: json.dump(user_data, f, indent=4, ensure_ascii=False) with open(data_path, "r", encoding="utf-8") as f: loaded = json.load(f) print("Loaded from file:", loaded["username"]) # 3. Custom encoder โ handle datetime & Decimal class PynfinityEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() if isinstance(obj, Decimal): return float(obj) return super().default(obj) event = { "event" : "course_completed", "user" : "dhruv", "timestamp": datetime.now(), "price_paid": Decimal("999.00"), } print("\nCustom encoded:") print(json.dumps(event, cls=PynfinityEncoder, indent=2)) # 4. Pretty-print nested JSON nested = {"pynfinity": {"courses": [{"name": "Python", "modules": 20}, {"name": "AI", "modules": 26}]}} print("\nPretty nested:") print(json.dumps(nested, indent=4)) # Cleanup data_path.unlink(missing_ok=True)
Keep exploring and happy coding! ๐ป