Certainly! Below is a minimal but functional Python implementation of a FLATSON encoder and decoder.
It supports:
- Parsing lines into nested dicts/lists
- Typed values (
i, f, b, t, s)
- Encoding nested dict/list back to FLATSON lines
- Comments and pragmas are ignored in parsing and not emitted in encoding (can be extended)
- Here-doc multiline values are not implemented in this minimal example (can be added later)
Python code
import re
from datetime import datetime
from typing import Any, Union
# Regex to parse a line: path = [type:]value
LINE_RE = re.compile(r'''
^\s*
(?P<path>[a-zA-Z0-9_\-\.]+(?:\[[0-9]+\])*) # path with optional array indices
\s*=\s*
(?P<value>.+)
$
''', re.VERBOSE)
# Regex to parse type prefix in value: e.g. i:42, s:"hello"
TYPE_RE = re.compile(r'^(?P<type>[ifbts]):(?P<val>.+)$')
# Regex to parse array indices in path segments
PATH_SEG_RE = re.compile(r'([a-zA-Z0-9_\-]+)(?:\[(\d+)\])?')
def parse_literal(typ: str, val: str) -> Any:
val = val.strip()
if typ == 's':
# Remove quotes if present
if val.startswith('"') and val.endswith('"'):
val = val[1:-1]
val = val.replace('\\"', '"').replace('\\\\', '\\')
return val
elif typ == 'i':
return int(val)
elif typ == 'f':
return float(val)
elif typ == 'b':
if val.lower() in ('true', '1'):
return True
elif val.lower() in ('false', '0'):
return False
else:
raise ValueError(f"Invalid boolean value: {val}")
elif typ == 't':
# ISO8601 parse (basic)
return datetime.fromisoformat(val.replace('Z', '+00:00'))
else:
raise ValueError(f"Unknown type tag: {typ}")
def encode_literal(val: Any) -> str:
if isinstance(val, bool):
return f"b:{str(val).lower()}"
elif isinstance(val, int):
return f"i:{val}"
elif isinstance(val, float):
return f"f:{val}"
elif isinstance(val, datetime):
# ISO8601 format with Z for UTC
s = val.isoformat()
if s.endswith('+00:00'):
s = s[:-6] + 'Z'
return f"t:{s}"
elif isinstance(val, str):
# Quote if contains spaces or special chars
if re.search(r'\s|=|"', val):
escaped = val.replace('\\', '\\\\').replace('"', '\\"')
return f'"{escaped}"'
else:
return val
else:
raise TypeError(f"Unsupported type for encoding: {type(val)}")
def parse_path(path: str):
"""Parse dot and array-indexed path into list of (key, index) tuples."""
parts = []
for match in PATH_SEG_RE.finditer(path):
key = match.group(1)
idx = match.group(2)
if idx is not None:
parts.append((key, int(idx)))
else:
parts.append((key, None))
return parts
def insert_value(tree: dict, path_parts, value):
"""Insert value into nested dict/list structure following path_parts."""
current = tree
for i, (key, idx) in enumerate(path_parts):
is_last = (i == len(path_parts) - 1)
if idx is None:
# dict key
if is_last:
current[key] = value
else:
if key not in current or not isinstance(current[key], dict):
current[key] = {}
current = current[key]
else:
# list index
if key not in current or not isinstance(current[key], list):
current[key] = []
lst = current[key]
# Expand list if needed
while len(lst) <= idx:
lst.append(None)
if is_last:
lst[idx] = value
else:
if lst[idx] is None or not isinstance(lst[idx], dict):
lst[idx] = {}
current = lst[idx]
def decode_flatson(text: str) -> dict:
tree = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith(('#', '//', '@')):
continue
m = LINE_RE.match(line)
if not m:
raise ValueError(f"Invalid line: {line}")
path = m.group('path')
val_raw = m.group('value').strip()
# Detect type prefix
mtype = TYPE_RE.match(val_raw)
if mtype:
typ = mtype.group('type')
val_str = mtype.group('val').strip()
else:
# Default to string, remove quotes if any
typ = 's'
val_str = val_raw
val = parse_literal(typ, val_str)
path_parts = parse_path(path)
insert_value(tree, path_parts, val)
return tree
def flatten(tree: Union[dict, list], prefix='') -> list:
"""Flatten nested dict/list into list of (path, value) tuples."""
lines = []
if isinstance(tree, dict):
for k in sorted(tree.keys()):
v = tree[k]
new_prefix = f"{prefix}.{k}" if prefix else k
lines.extend(flatten(v, new_prefix))
elif isinstance(tree, list):
for i, v in enumerate(tree):
new_prefix = f"{prefix}[{i}]"
lines.extend(flatten(v, new_prefix))
else:
lines.append((prefix, tree))
return lines
def encode_flatson(tree: dict) -> str:
lines = []
for path, val in flatten(tree):
val_str = encode_literal(val)
# If val_str already has type prefix (like i:42), just output as is
# If val_str is quoted string or untyped string, output as is
# We rely on encode_literal to produce correct output
lines.append(f"{path} = {val_str}")
return "\n".join(lines)
# Example usage
if __name__ == "__main__":
sample = """
user.id:i = 99
user.name = "Charlie"
user.roles[0] = "admin"
user.roles[1] = "developer"
user.active:b = true
user.prefs.theme = "dark"
user.prefs.volume:f = 0.8
"""
data = decode_flatson(sample)
print("Decoded data:")
print(data)
encoded = encode_flatson(data)
print("\nRe-encoded FLATSON:")
print(encoded)
Explanation
decode_flatson reads FLATSON text, skips comments/empty lines, parses each line into path + typed value, and builds a nested dict/list structure.
encode_flatson takes a nested dict/list and produces FLATSON lines, sorting keys lexicographically for canonical order.
parse_path handles dot notation and array indices.
parse_literal and encode_literal handle type conversions and string quoting.
- The example at the bottom shows decoding and re-encoding the sample from the spec.
If you want, I can help extend this with:
- Here-doc multiline support
- Comments preservation
- More robust escaping
- Streaming parser / writer
Just ask!