Below is a self-contained “mini parser-combinator” library (≈90 lines) plus a JSON parser built with it.
Feed it any JSON text and it will give you the corresponding Python value. At the end you’ll see it in action on a handful of different JSON snippets.
# ------------------ tiny_parser.py ------------------
import re
from typing import Callable, Tuple, Any
class ParseError(Exception):
"""Raised when a parser fails."""
pass
class Parser:
"""A parser is simply a callable: (text, pos) -> (value, new_pos)."""
def __init__(self, func: Callable[[str, int], Tuple[Any, int]]):
self.func = func
# make instances callable
def __call__(self, text: str, pos: int = 0):
return self.func(text, pos)
# Combinators ---------------------------------------------------
def map(self, f):
return Parser(lambda s, i: _apply(f, self(s, i)))
def then(self, other): # keep both results (a , b)
return Parser(lambda s, i: _then(self, other, s, i))
def skip(self, other): # keep left only
return Parser(lambda s, i: _skip(self, other, s, i))
def before(self, other): # keep right only
return Parser(lambda s, i: _before(self, other, s, i))
def or_else(self, other):
return Parser(lambda s, i: _or_else(self, other, s, i))
# Convenience: >> and << operators (Haskell style)
def __rshift__(self, other): # keep right
return self.before(other)
def __lshift__(self, other): # keep left
return self.skip(other)
def _apply(f, res):
val, pos = res
return f(val), pos
def _then(p1, p2, s, i):
v1, i1 = p1(s, i)
v2, i2 = p2(s, i1)
return (v1, v2), i2
def _skip(p1, p2, s, i):
v, i1 = p1(s, i)
_, i2 = p2(s, i1)
return v, i2
def _before(p1, p2, s, i):
_, i1 = p1(s, i)
v, i2 = p2(s, i1)
return v, i2
def _or_else(p1, p2, s, i):
try:
return p1(s, i)
except ParseError:
return p2(s, i)
# Low-level primitives --------------------------------------------
def literal(token: str) -> Parser:
L = len(token)
return Parser(lambda s, i:
(token, i+L) if s.startswith(token, i) else _fail(i, f"'{token}'"))
def regex(pattern: str) -> Parser:
compiled = re.compile(pattern)
return Parser(lambda s, i:
_match(compiled, s, i))
def _match(r, s, i):
m = r.match(s, i)
if not m:
_fail(i, f"regex {r.pattern}")
return m.group(0), m.end()
def _fail(pos, msg):
raise ParseError(f"Expecting {msg} at position {pos}")
# Helpers ----------------------------------------------------------
def separated(p_elem: Parser, p_sep: Parser):
"""Parse p_elem (sep p_elem)* -> [elem, elem, ...] (can be empty)."""
def parse(s, i):
elems = []
try:
v, i = p_elem(s, i)
elems.append(v)
while True:
_, i = p_sep(s, i)
v, i = p_elem(s, i)
elems.append(v)
except ParseError:
pass
return elems, i
return Parser(parse)
class Forward(Parser):
"""Placeholder for recursive definitions."""
def __init__(self):
super().__init__(self._unset)
def _unset(self, *_):
raise ParseError("Forward parser not set yet")
def set(self, p: Parser):
self.func = p.func
whitespace = regex(r'\s*')
def token(p: Parser):
"""Parser that skips trailing whitespace."""
return (p << whitespace)
# -------------- JSON parser built with the framework ----------
value = Forward() # Forward declaration
# literals
j_null = token(literal("null")).map(lambda _: None)
j_true = token(literal("true")).map(lambda _: True)
j_false = token(literal("false")).map(lambda _: False)
# numbers (int / float / exp)
number_re = r'-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?'
j_number = token(regex(number_re)).map(lambda x: float(x) if ('.' in x or 'e' in x or 'E' in x) else int(x))
# strings (with basic escapes)
escape_dict = {'"':'"', '\\':'\\', '/':'/', 'b':'\b', 'f':'\f', 'n':'\n', 'r':'\r', 't':'\t'}
def _decode_string(raw: str) -> str:
i, out = 0, []
while i < len(raw):
ch = raw[i]
if ch != '\\':
out.append(ch); i += 1; continue
i += 1
esc = raw[i]
if esc == 'u': # \uXXXX
out.append(chr(int(raw[i+1:i+5], 16)))
i += 5
else:
out.append(escape_dict.get(esc, esc))
i += 1
return ''.join(out)
string_body = regex(r'"((?:[^"\\]|\\.)*)"') # capture content without outer quotes
j_string = token(string_body).map(lambda m: _decode_string(m[1:-1]))
# arrays [ v , v , ... ]
left_bracket = token(literal('['))
right_bracket = token(literal(']'))
comma = token(literal(','))
def build_array(vals): return list(vals)
j_array = (left_bracket >>
separated(value, comma).map(build_array) <<
right_bracket)
# objects { "k":v , ... }
left_brace = token(literal('{'))
right_brace = token(literal('}'))
colon = token(literal(':'))
def member_parser():
key = j_string
return (key << colon).then(value).map(lambda kv: (kv[0], kv[1]))
members = separated(member_parser(), comma)
j_object = (left_brace >>
members.map(lambda kvs: dict(kvs)) <<
right_brace)
# tie the knot for 'value'
value.set(
j_string.or_else(j_number)
.or_else(j_object)
.or_else(j_array)
.or_else(j_true)
.or_else(j_false)
.or_else(j_null)
)
# convenience front-end
def parse_json(text: str):
val, pos = whitespace(text, 0) # skip leading ws
val, pos = value(text, pos)
_, pos = whitespace(text, pos) # skip trailing ws
if pos != len(text):
raise ParseError(f"Extra data at position {pos}")
return val
# ------------------ Demo / Quick tests ------------------------
if __name__ == "__main__":
samples = [
'null',
'true',
'false',
'123',
'-3.14e10',
'"hello \\"world\\""',
'[1, 2, 3]',
'{"a": 1, "b": [true, null, "x"]}',
'{ "nested" : { "array" : [ 1 , { "obj": false } ] } }'
]
for s in samples:
print(f"In : {s}")
print(f"Out: {parse_json(s)}")
print("-" * 40)
A quick run produces:
In : null
Out: None
----------------------------------------
In : true
Out: True
----------------------------------------
In : false
Out: False
----------------------------------------
In : 123
Out: 123
----------------------------------------
In : -3.14e10
Out: -31400000000.0
----------------------------------------
In : "hello \"world\""
Out: hello "world"
----------------------------------------
In : [1, 2, 3]
Out: [1, 2, 3]
----------------------------------------
In : {"a": 1, "b": [true, null, "x"]}
Out: {'a': 1, 'b': [True, None, 'x']}
----------------------------------------
In : { "nested" : { "array" : [ 1 , { "obj": false } ] } }
Out: {'nested': {'array': [1, {'obj': False}]}}
----------------------------------------
Feel free to import parse_json and throw any JSON at it—so long as it’s valid, you should get a faithful Python representation back 🚀