Skip to content

JSON FILE OPERATIONS - Reading and writing JSON data

Python
#!/usr/bin/env python3
"""
JSON FILE OPERATIONS - Reading and writing JSON data
Demonstrates working with JSON formatted files
"""

import os
import tempfile
import json

print("=" * 60)
print("JSON FILE OPERATIONS - JavaScript Object Notation")
print("=" * 60)

temp_dir = tempfile.gettempdir()

# Example 1: Writing JSON manually
print("\n1. Writing JSON Data Manually")
print("-" * 40)
json_file = os.path.join(temp_dir, "config.json")

json_text = """{
    "app_name": "MyApp",
    "version": "1.0.0",
    "debug": true,
    "max_connections": 100
}"""

with open(json_file, 'w') as f:
    f.write(json_text)

print(f"Created: {json_file}")
print("Content:")
print(json_text)

# Example 2: Reading JSON manually
print("\n2. Reading JSON File")
print("-" * 40)
with open(json_file, 'r') as f:
    content = f.read()
    print("Raw JSON string:")
    print(content)

# Example 3: Using json module to write
print("\n3. Using json.dump() to Write")
print("-" * 40)
data = {
    "users": [
        {"id": 1, "name": "Alice", "active": True},
        {"id": 2, "name": "Bob", "active": False},
        {"id": 3, "name": "Charlie", "active": True}
    ],
    "total_count": 3,
    "last_updated": "2024-01-15"
}

users_file = os.path.join(temp_dir, "users.json")
with open(users_file, 'w') as f:
    json.dump(data, f, indent=2)

print(f"Created: {users_file}")
print("Data structure written to JSON")

# Example 4: Using json module to read
print("\n4. Using json.load() to Read")
print("-" * 40)
with open(users_file, 'r') as f:
    loaded_data = json.load(f)

print(f"Loaded {loaded_data['total_count']} users:")
for user in loaded_data['users']:
    status = "Active" if user['active'] else "Inactive"
    print(f"  {user['name']} (ID: {user['id']}): {status}")

# Example 5: Pretty printing JSON
print("\n5. Pretty Printing JSON")
print("-" * 40)
pretty_file = os.path.join(temp_dir, "pretty.json")

data = {"name": "Widget", "price": 19.99, "tags": ["new", "sale", "featured"], "in_stock": True}

with open(pretty_file, 'w') as f:
    json.dump(data, f, indent=4, sort_keys=True)

print("With indent=4, sort_keys=True:")
with open(pretty_file, 'r') as f:
    print(f.read())

# Example 6: Compact JSON (no whitespace)
print("\n6. Compact JSON (No Whitespace)")
print("-" * 40)
compact_file = os.path.join(temp_dir, "compact.json")

with open(compact_file, 'w') as f:
    json.dump(data, f, separators=(',', ':'))

print("Compact format:")
with open(compact_file, 'r') as f:
    print(f.read())

# Example 7: Updating JSON file
print("\n7. Reading, Modifying, and Writing JSON")
print("-" * 40)

# Read existing data
with open(users_file, 'r') as f:
    data = json.load(f)

# Modify
data['users'].append({"id": 4, "name": "Diana", "active": True})
data['total_count'] = len(data['users'])
data['last_updated'] = "2024-01-16"

# Write back
with open(users_file, 'w') as f:
    json.dump(data, f, indent=2)

print("Added new user, updated count and date")

# Verify
with open(users_file, 'r') as f:
    updated = json.load(f)
    print(f"New total: {updated['total_count']} users")

# Example 8: JSON with complex nested data
print("\n8. Complex Nested JSON Structure")
print("-" * 40)
complex_file = os.path.join(temp_dir, "complex.json")

complex_data = {
    "company": {
        "name": "TechCorp",
        "founded": 2010,
        "departments": [
            {
                "name": "Engineering",
                "employees": [
                    {"name": "Alice", "role": "Developer"},
                    {"name": "Bob", "role": "Architect"}
                ]
            },
            {
                "name": "Sales",
                "employees": [
                    {"name": "Charlie", "role": "Manager"}
                ]
            }
        ]
    }
}

with open(complex_file, 'w') as f:
    json.dump(complex_data, f, indent=2)

# Read and navigate
with open(complex_file, 'r') as f:
    data = json.load(f)

print(f"Company: {data['company']['name']}")
for dept in data['company']['departments']:
    print(f"  {dept['name']} Department:")
    for emp in dept['employees']:
        print(f"    - {emp['name']} ({emp['role']})")

# Example 9: Handling JSON errors
print("\n9. Handling Invalid JSON")
print("-" * 40)
bad_json_file = os.path.join(temp_dir, "bad.json")

with open(bad_json_file, 'w') as f:
    f.write('{"name": "test", "value": }')  # Invalid JSON

try:
    with open(bad_json_file, 'r') as f:
        data = json.load(f)
except json.JSONDecodeError as e:
    print(f"  Error: {e}")
    print(f"  Line {e.lineno}, Column {e.colno}")

# Example 10: JSON array at root
print("\n10. JSON Array as Root Element")
print("-" * 40)
array_file = os.path.join(temp_dir, "array.json")

items = ["apple", "banana", "cherry", "date"]

with open(array_file, 'w') as f:
    json.dump(items, f)

with open(array_file, 'r') as f:
    loaded_items = json.load(f)
    print(f"Loaded {len(loaded_items)} items:")
    for i, item in enumerate(loaded_items, 1):
        print(f"  {i}. {item}")

# Example 11: Building JSON incrementally (wrong way)
print("\n11. JSON Must Be Written Complete")
print("-" * 40)
print("  Note: Cannot append to JSON like text files")
print("  Must read entire structure, modify, write complete")

incremental_file = os.path.join(temp_dir, "incremental.json")

# Start with empty list
data = []

# Add items
data.append({"id": 1, "value": "first"})
data.append({"id": 2, "value": "second"})

# Write complete structure
with open(incremental_file, 'w') as f:
    json.dump(data, f, indent=2)

print("  Written complete JSON array")

# Cleanup
for f in [json_file, users_file, pretty_file, compact_file,
          complex_file, bad_json_file, array_file, incremental_file]:
    if os.path.exists(f):
        os.remove(f)

print("\n" + "=" * 60)
print("Key Points:")
print("  - JSON = structured data format")
print("  - json.dump() writes Python → JSON")
print("  - json.load() reads JSON → Python")
print("  - Use indent for readability")
print("  - Must write complete structure each time")
print("=" * 60)