🌱 Junior Track 28 of 29

28. JSON & Data Processing

Serialize and deserialize structured data using Python's standard `json` module. Master `json.dumps()`, `json.loads()`, file I/O with `json.dump()`/`json.load()`, API payload parsing, and custom encoders.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 28 — JSON & DATA PROCESSING
# ==============================================================================
import json
from datetime import datetime

# 1. Serialization: Converting Python Data (Dict) to JSON String (dumps)
user_profile = {
    "id": 101,
    "username": "shkar_dev",
    "is_active": True,
    "roles": ["admin", "developer"],
    "metadata": {"last_login": "2026-09-20", "login_count": 42},
    "notes": None
}

# Pretty-print with indentation & sorted keys
json_str = json.dumps(user_profile, indent=2, sort_keys=True)


# 2. Deserialization: Parsing JSON String to Python Dict (loads)
raw_api_response = """
{
    "status": 200,
    "payload": {
        "items": ["Python", "Flask", "JSON"],
        "total": 3,
        "cached": false
    }
}
"""
parsed_dict = json.loads(raw_api_response)


# 3. File I/O: Serializing to Disk File (dump) & Reading from File (load)
def save_config_to_file(filename: str, data: dict):
    with open(filename, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=4)

def load_config_from_file(filename: str) -> dict:
    with open(filename, "r", encoding="utf-8") as f:
        return json.load(f)


# 4. Custom Serialization Handler for Non-JSON Native Types (datetime)
def custom_json_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")

event_data = {
    "event_id": "EVT-9001",
    "created_at": datetime(2026, 9, 20, 20, 30, 0)
}
custom_json = json.dumps(event_data, default=custom_json_serializer, indent=2)


if __name__ == "__main__":
    print("=== 1. Serialized User Profile JSON ===")
    print(json_str)

    print("\n=== 2. Deserialized API Response Dict ===")
    print(f"Status Code: {parsed_dict['status']}")
    print(f"Total Items: {parsed_dict['payload']['total']}")

    print("\n=== 3. Custom DateTime Serialized Output ===")
    print(custom_json)
🌱 Junior Track 28 Master Reference

28. Python ↔ JSON Type Conversion & API Reference

🛠️ Python Standard `json` API Functions

Function Operation Input Type Output Type
json.dumps(obj) Serialize Python Object (`dict`, `list`) JSON `str`
json.loads(str) Deserialize JSON `str` / `bytes` Python Object (`dict`, `list`)
json.dump(obj, fp) File Write Python Object + File Pointer Written `.json` Disk File
json.load(fp) File Read File Pointer (`.json` file) Python Object (`dict`, `list`)

🔄 Python ↔ JSON Type Mapping Matrix

Python Data Type JSON Data Equivalent Example
dict object `{"key": "value"}`
list, tuple array [1, 2, "three"]
str string "hello world"
int, float number 42, 3.14159
True / False true / false true, false
None null null

⭐ Rate Track 28: JSON & Data Serialization (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 27. Logging & Diagnostics 🌱 Junior Hub Next Track: 29. Regular Expressions →