Sure! I'll first implement a small parser combinator framework in Python, then build a JSON parser on top of it, and finally demonstrate parsing various JSON strings.
Step 1: Parser Combinator Framework
A parser combinator is a higher-order function that accepts several parsers as input and returns a new parser as output. Each parser is a function that takes an input string and returns a list of (result, remaining_string) pairs (to support backtracking and ambiguity).
Here's a minimal but functional parser combinator framework:
from typing import Callable, List, Tuple, Any, Optional
Parser = Callable[[str], List[Tuple[Any, str]]]
def pure(value: Any) -> Parser:
def parser(s: str) -> List[Tuple[Any, str]]:
return [(value, s)]
return parser
def fail() -> Parser:
def parser(s: str) -> List[Tuple[Any, str]]:
return []
return parser
def item() -> Parser:
def parser(s: str) -> List[Tuple[str, str]]:
if s:
return [(s[0], s[1:])]
else:
return []
return parser
def satisfy(predicate: Callable[[str], bool]) -> Parser:
def parser(s: str) -> List[Tuple[str, str]]:
if s and predicate(s[0]):
return [(s[0], s[1:])]
else:
return []
return parser
def char(c: str) -> Parser:
return satisfy(lambda x: x == c)
def one_of(chars: str) -> Parser:
return satisfy(lambda c: c in chars)
def string(str_to_match: str) -> Parser:
if not str_to_match:
return pure("")
else:
first, rest = str_to_match[0], str_to_match[1:]
return bind(char(first), lambda _: bind(string(rest), lambda _: pure(str_to_match)))
def bind(p: Parser, f: Callable[[Any], Parser]) -> Parser:
def parser(s: str) -> List[Tuple[Any, str]]:
results = []
for (v, s2) in p(s):
results.extend(f(v)(s2))
return results
return parser
def choice(p1: Parser, p2: Parser) -> Parser:
def parser(s: str) -> List[Tuple[Any, str]]:
return p1(s) + p2(s)
return parser
def many(p: Parser) -> Parser:
def parser(s: str) -> List[Tuple[List[Any], str]]:
results = [([], s)]
for (v, s2) in p(s):
for (vs, s3) in parser(s2):
results.append(([v] + vs, s3))
return results
return parser
def many1(p: Parser) -> Parser:
return bind(p, lambda v: bind(many(p), lambda vs: pure([v] + vs)))
def sep_by(p: Parser, sep: Parser) -> Parser:
return choice(
bind(p, lambda v: bind(many(bind(sep, lambda _: p)), lambda vs: pure([v] + vs))),
pure([])
)
def whitespace() -> Parser:
return many(one_of(" \t\n\r"))
def token(p: Parser) -> Parser:
return bind(p, lambda v: bind(whitespace(), lambda _: pure(v)))
def digit() -> Parser:
return satisfy(str.isdigit)
def number() -> Parser:
def to_number(chars):
return int("".join(chars))
sign = choice(char('-'), pure(''))
digits = many1(digit())
def parser(s: str):
results = []
for (sgn, s2) in sign(s):
for (ds, s3) in digits(s2):
val = int("".join(ds))
if sgn == '-':
val = -val
results.append((val, s3))
return results
return parser
Step 2: JSON Parser
Now let's build a JSON parser using the above combinators. We'll support:
null
true / false
- numbers (integers and floats)
- strings (with basic escape handling)
- arrays
- objects
import re
def json_null() -> Parser:
return bind(string("null"), lambda _: pure(None))
def json_bool() -> Parser:
return choice(
bind(string("true"), lambda _: pure(True)),
bind(string("false"), lambda _: pure(False))
)
def json_number() -> Parser:
# More complete number parser with floats and exponents
number_re = re.compile(r'-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?')
def parser(s: str):
m = number_re.match(s)
if not m:
return []
num_str = m.group(0)
rest = s[len(num_str):]
if '.' in num_str or 'e' in num_str or 'E' in num_str:
return [(float(num_str), rest)]
else:
return [(int(num_str), rest)]
return parser
def json_string() -> Parser:
# Parse JSON strings with escapes
def parser(s: str):
if not s or s[0] != '"':
return []
i = 1
result = []
while i < len(s):
c = s[i]
if c == '"':
return [("".join(result), s[i+1:])]
if c == '\\':
i += 1
if i >= len(s):
return []
esc = s[i]
if esc == '"':
result.append('"')
elif esc == '\\':
result.append('\\')
elif esc == '/':
result.append('/')
elif esc == 'b':
result.append('\b')
elif esc == 'f':
result.append('\f')
elif esc == 'n':
result.append('\n')
elif esc == 'r':
result.append('\r')
elif esc == 't':
result.append('\t')
elif esc == 'u':
# Unicode escape
if i + 4 >= len(s):
return []
hex_digits = s[i+1:i+5]
if not all(c in "0123456789abcdefABCDEF" for c in hex_digits):
return []
result.append(chr(int(hex_digits, 16)))
i += 4
else:
return []
else:
result.append(c)
i += 1
return []
return parser
def json_array() -> Parser:
def parser(s: str):
# Parse [ elements ]
if not s or s[0] != '[':
return []
s = s[1:]
s = s.lstrip()
elements = []
if s and s[0] == ']':
return ([], s[1:])
while True:
vals = json_value()(s)
if not vals:
return []
(val, s) = vals[0]
elements.append(val)
s = s.lstrip()
if s and s[0] == ',':
s = s[1:].lstrip()
continue
elif s and s[0] == ']':
return [(elements, s[1:])]
else:
return []
return parser
def json_object() -> Parser:
def parser(s: str):
if not s or s[0] != '{':
return []
s = s[1:].lstrip()
obj = {}
if s and s[0] == '}':
return [(obj, s[1:])]
while True:
key_vals = json_string()(s)
if not key_vals:
return []
(key, s) = key_vals[0]
s = s.lstrip()
if not s or s[0] != ':':
return []
s = s[1:].lstrip()
val_vals = json_value()(s)
if not val_vals:
return []
(val, s) = val_vals[0]
obj[key] = val
s = s.lstrip()
if s and s[0] == ',':
s = s[1:].lstrip()
continue
elif s and s[0] == '}':
return [(obj, s[1:])]
else:
return []
return parser
def json_value() -> Parser:
def parser(s: str):
s = s.lstrip()
for p in [json_null(), json_bool(), json_number(), json_string(), json_array(), json_object()]:
res = p(s)
if res:
return res
return []
return parser
def parse_json(s: str) -> Any:
res = json_value()(s)
for (val, rest) in res:
if rest.lstrip() == '':
return val
raise ValueError("Invalid JSON or trailing characters")
Step 3: Testing the JSON parser
test_jsons = [
'null',
'true',
'false',
'123',
'-123',
'3.1415',
'"hello world"',
'"escaped \\"quote\\""',
'[]',
'[1, 2, 3]',
'[true, false, null, "text", 123]',
'{}',
'{"key": "value", "num": 42, "bool": true, "arr": [1,2,3]}',
'''
{
"name": "ChatGPT",
"features": ["language understanding", "code generation", "reasoning"],
"active": true,
"version": 3.5,
"nullValue": null
}
'''
]
for js in test_jsons:
print(f"Input: {js}")
try:
result = parse_json(js)
print("Parsed:", result)
except Exception as e:
print("Error:", e)
print("-" * 40)
Explanation
- The parser combinator framework is minimal but supports sequencing (
bind), choice (choice), repetition (many), and basic token parsing.
- The JSON parser uses these combinators and some manual parsing (especially for strings and arrays/objects) to handle JSON syntax.
- The test cases cover a variety of JSON values.
If you want, I can also provide a more functional or monadic style parser combinator framework or extend the JSON parser to support more features. Let me know!