PYTHON

Efficiently Query Nested JSON-like Data Structures

Navigate and extract data from complex, deeply nested dictionary and list structures, common in API responses or configuration files, using Python's recursive approach.

def get_nested_value(data: dict, keys: list, default=None):
    """Recursively retrieves a value from a nested dictionary using a list of keys."""
    current = data
    for key in keys:
        if isinstance(current, dict) and key in current:
            current = current[key]
        elif isinstance(current, list) and isinstance(key, int) and 0 <= key < len(current):
            current = current[key]
        else:
            return default # Key not found at current level
    return current

# Example JSON-like data (e.g., from an API response)
api_response = {
    "user": {
        "id": "123",
        "profile": {
            "name": "Alice Smith",
            "email": "[email protected]",
            "settings": {
                "notifications": True,
                "theme": "dark"
            }
        },
        "orders": [
            {"id": "A001", "status": "shipped"},
            {"id": "A002", "status": "pending"}
        ]
    },
    "metadata": {"timestamp": "2023-10-27"}
}

# Querying nested dictionary values
user_email = get_nested_value(api_response, ['user', 'profile', 'email'])
print(f"User Email: {user_email}") # Output: User Email: [email protected]

# Querying nested list elements
first_order_status = get_nested_value(api_response, ['user', 'orders', 0, 'status'])
print(f"First Order Status: {first_order_status}") # Output: First Order Status: shipped

# Querying non-existent path with default value
non_existent = get_nested_value(api_response, ['user', 'profile', 'address', 'city'], default='N/A')
print(f"Non-existent path: {non_existent}") # Output: Non-existent path: N/A

# Querying deeply nested value
user_theme = get_nested_value(api_response, ['user', 'profile', 'settings', 'theme'])
print(f"User Theme: {user_theme}") # Output: User Theme: dark
How it works: Web developers frequently work with complex, nested data structures, often returned from APIs as JSON. This snippet provides a robust function, `get_nested_value`, to safely extract data from such structures (dictionaries and lists) using a list of keys. It iterates through the provided keys, handling both dictionary keys and list indices, and gracefully returns a default value if any part of the path is not found. This prevents `KeyError` or `IndexError` and simplifies data extraction logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs