import json
from django import template

register = template.Library()

@register.filter(name='from_json')
def from_json(json_string):
    """
    Safely loads a JSON string into a Python object (list or dict).
    """
    try:
        # The JSON string comes from the context and needs to be parsed
        return json.loads(json_string)
    except (TypeError, json.JSONDecodeError):
        # Handle cases where the string is invalid or None/empty
        return []


@register.filter(name='split')
def split_string(value, key=None):
    """Splits a string by the given key (default is space)."""
    if key is None:
        return value.split()
    return value.split(key)