🔗 Working with JSON Files

JSON (JavaScript Object Notation) is a popular data format for configuration files, APIs, and data exchange. Python's json module makes it easy to work with JSON data.

import json

# Basic JSON operations
data = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Write to JSON file
with open('data.json', 'w') as file:
    json.dump(data, file)

# Read from JSON file
with open('data.json', 'r') as file:
    loaded_data = json.load(file)
    print(loaded_data)

🎯 JSON Operations

Python offers several approaches to work with JSON data.

Working with Data Types

import json

# JSON with different data types
data = {
    'name': 'Alice',
    'age': 25,
    'grades': [85, 92, 78],
    'is_student': True,
    'address': {
        'street': '123 Main St',
        'city': 'New York'
    }
}

# Write JSON with formatting
with open('formatted.json', 'w') as file:
    json.dump(data, file, indent=4, sort_keys=True)

print("JSON file written with formatting")

Reading and String Operations

# Read JSON file
with open('formatted.json', 'r') as file:
    loaded_data = json.load(file)
    print(f"Loaded data: {loaded_data}")

# Working with JSON strings
json_string = json.dumps(data, indent=2)
print(f"JSON string (first 100 chars):\n{json_string[:100]}...")

# Parse JSON string
parsed_data = json.loads(json_string)
print(f"Parsed name: {parsed_data['name']}")

Working with Lists

# JSON with list data
students = [
    {'name': 'Alice', 'grade': 'A'},
    {'name': 'Bob', 'grade': 'B'},
    {'name': 'Charlie', 'grade': 'C'}
]

with open('students.json', 'w') as file:
    json.dump(students, file, indent=2)

with open('students.json', 'r') as file:
    student_list = json.load(file)
    for student in student_list:
        print(f"{student['name']}: {student['grade']}")

🔍 Advanced JSON Handling

Python allows sophisticated JSON operations and error handling.

Custom Encoders

import json
from datetime import datetime

# Custom JSON encoder for complex types
class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

# Example with datetime
data_with_date = {
    'name': 'Alice',
    'created_at': datetime.now(),
    'scores': [85, 92, 78]
}

# Write with custom encoder
with open('data_with_date.json', 'w') as file:
    json.dump(data_with_date, file, cls=DateTimeEncoder, indent=2)

print("JSON with custom encoder written")

Safe Operations

from pathlib import Path

# Safe JSON operations with error handling
def safe_json_read(filename):
    """Safely read JSON file with error handling"""
    try:
        with open(filename, 'r') as file:
            return json.load(file)
    except FileNotFoundError:
        print(f"File {filename} not found")
        return None
    except json.JSONDecodeError as e:
        print(f"Invalid JSON in {filename}: {e}")
        return None
    except Exception as e:
        print(f"Error reading {filename}: {e}")
        return None

def safe_json_write(data, filename):
    """Safely write JSON file with error handling"""
    try:
        # Create directory if it doesn't exist
        Path(filename).parent.mkdir(parents=True, exist_ok=True)
        
        with open(filename, 'w') as file:
            json.dump(data, file, indent=2, ensure_ascii=False)
        return True
    except Exception as e:
        print(f"Error writing {filename}: {e}")
        return False

# Example usage
config_data = safe_json_read('config.json')
if config_data:
    print(f"Config loaded: {config_data}")

Nested Data and Validation

# Working with nested JSON
nested_data = {
    'users': [
        {
            'id': 1,
            'name': 'Alice',
            'profile': {
                'email': 'alice@example.com',
                'preferences': {
                    'theme': 'dark',
                    'notifications': True
                }
            }
        }
    ]
}

safe_json_write(nested_data, 'nested_data.json')

# JSON validation
def validate_json_structure(data, required_fields):
    """Validate JSON data has required fields"""
    if not isinstance(data, dict):
        return False, "Data must be a dictionary"
    
    missing_fields = []
    for field in required_fields:
        if field not in data:
            missing_fields.append(field)
    
    if missing_fields:
        return False, f"Missing fields: {missing_fields}"
    
    return True, "Valid"

# Example validation
user_data = {'name': 'Alice', 'email': 'alice@example.com'}
is_valid, message = validate_json_structure(user_data, ['name', 'email', 'age'])
print(f"Validation: {message}")

Utility Functions

# Merging JSON files
def merge_json_files(*filenames):
    """Merge multiple JSON files into one"""
    merged_data = {}
    
    for filename in filenames:
        data = safe_json_read(filename)
        if data:
            merged_data.update(data)
    
    return merged_data

# Pretty print JSON
def pretty_print_json(data):
    """Pretty print JSON data"""
    print(json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False))

# Example usage
pretty_print_json(nested_data)
print("JSON utility functions demonstrated")

📋 JSON Parameters Reference Table

ParameterPurposeValues
indentPretty formatting2, 4, None
sort_keysSort dictionary keysTrue, False
ensure_asciiUse only ASCII charactersTrue, False
separatorsCustom separators(',', ':'), (', ', ': ')
clsCustom encoder classDateTimeEncoder, etc.

🎯 Key Takeaways

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent