import json
import re

def extract_path(obj, path):
    parts = re.split(r'\.(?![^\[]*\])', path)
    current = obj
    try:
        for part in parts:
            match = re.match(r'([^\[]+)(?:\[(\d+)\])?', part)
            if not match:
                return None
            key, idx = match.groups()
            current = current[key]
            if idx is not None:
                current = current[int(idx)]
        return current
    except (KeyError, IndexError, TypeError):
        return None

def short_column_name(path):
    path = path.strip()
    last = re.split(r'\.(?![^\[]*\])', path)[-1]
    return re.sub(r'\[.*?\]', '', last)

def json_table(json_str, columns=None):
    data = json.loads(json_str)

    if isinstance(data, dict):
        data = [data]

    if columns is None:
        if isinstance(data[0], dict):
            columns = list(data[0].keys())
            header = columns
    else:
        header = [short_column_name(col) for col in columns]

    yield valentina.TableHeader(header)

    for item in data:
        yield [extract_path(item, col) for col in columns]

def valentina_extension_init(db):
    valentina.create_procedure('json_table', json_table)
