import re
from datetime import datetime
# Regex for key path segment: letters, digits, _, -, dot-separated, with optional [index]
PATH_SEG_RE = re.compile(r'([a-zA-Z0-9_\-]+)(?:\[(\d+)\])?')
# Regex for a full line: key = [type:]value
LINE_RE = re.compile(r'''
^\s*
(?P<key>[a-zA-Z0-9_\-\.]+(?:\[\d+\])*) # key path
\s*=\s*
(?P<value>.+)
$
''', re.VERBOSE)
# Regex for type prefix
TYPE_RE = re.compile(r'^(?P<type>[ifbts]):(?P<val>.+)$')
def parse_line(line, lineno):
line = line.strip()
if not line or line.startswith(('#', '//', '@')):
return None # comment or metadata
m = LINE_RE.match(line)
if not m:
raise ValueError(f"Line {lineno}: Invalid syntax")
key = m.group('key')
raw_val = m.group('value').strip()
# Parse type prefix
mtype = TYPE_RE.match(raw_val)
if mtype:
typ = mtype.group('type')
val_str = mtype.group('val').strip()
else:
typ = 's'
val_str = raw_val
# Parse value by type
if typ == 'i':
try:
val = int(val_str)
except Exception:
raise ValueError(f"Line {lineno}: Invalid integer '{val_str}'")
elif typ == 'f':
try:
val = float(val_str)
except Exception:
raise ValueError(f"Line {lineno}: Invalid float '{val_str}'")
elif typ == 'b':
if val_str.lower() == 'true':
val = True
elif val_str.lower() == 'false':
val = False
else:
raise ValueError(f"Line {lineno}: Invalid boolean '{val_str}'")
elif typ == 't':
try:
# Strict ISO8601 UTC parsing
val = datetime.fromisoformat(val_str.replace('Z', '+00:00'))
except Exception:
raise ValueError(f"Line {lineno}: Invalid timestamp '{val_str}'")
elif typ == 's':
# Unquote if quoted
if val_str.startswith('"') and val_str.endswith('"'):
val = val_str[1:-1].replace('\\"', '"').replace('\\\\', '\\')
else:
val = val_str
else:
raise ValueError(f"Line {lineno}: Unknown type '{typ}'")
return key, val
def parse_flatson(text):
tree = {}
seen_keys = set()
for lineno, line in enumerate(text.splitlines(), 1):
try:
res = parse_line(line, lineno)
except Exception as e:
raise RuntimeError(f"Error parsing line {lineno}: {e}")
if res is None:
continue # comment or metadata
key, val = res
if key in seen_keys:
raise RuntimeError(f"Line {lineno}: Duplicate key '{key}'")
seen_keys.add(key)
# Insert into nested dict/list structure
insert_path(tree, key, val)
return tree
def insert_path(tree, key, val):
parts = PATH_SEG_RE.findall(key)
current = tree
for i, (k, idx) in enumerate(parts):
is_last = (i == len(parts) - 1)
if idx == '':
idx = None
else:
idx = int(idx)
if idx is None:
# dict key
if is_last:
current[k] = val
else:
if k not in current or not isinstance(current[k], dict):
current[k] = {}
current = current[k]
else:
# list index
if k not in current or not isinstance(current[k], list):
current[k] = []
lst = current[k]
while len(lst) <= idx:
lst.append(None)
if is_last:
lst[idx] = val
else:
if lst[idx] is None or not isinstance(lst[idx], dict):
lst[idx] = {}
current = lst[idx]