Build a Recursive-Descent Decoder for a JSON Subset
StringsAuto-graded · 20 test casesLast updated
Write a strict recursive-descent parser that turns JSON text into Python values and raises ValueError on any malformed input.
Decode JSON Text
Write a function decode_json_text(text) that reads a string containing one JSON document and returns the equivalent Python value. Do not use the json module or eval.
What must be supported
| JSON | Python result |
|---|---|
object { ... } | dict |
array [ ... ] | list |
string "..." | str |
| number | int or float |
true / false | True / False |
null | None |
Rules
- Whitespace. Space, tab (
\t), carriage return (\r) and newline (\n) may appear before or after any token, including inside empty containers such as[ ]and{ }and around the whole document. No other character counts as whitespace. - Objects. An object is
{, then zero or more"key" : valuemembers separated by commas, then}. Keys must be strings. If a key repeats, the last value wins. - Arrays. An array is
[, then zero or more values separated by commas, then]. - Strings. A string is enclosed in double quotes. The only escape sequences allowed are
\"(a quote) and\\(a backslash). Any other backslash sequence is malformed. A raw character with code below0x20inside a string is malformed. A string that never closes is malformed. - Numbers. A number follows the usual JSON grammar: an optional
-, then either a single0or a nonzero digit followed by more digits, then an optional fraction (.followed by one or more digits), then an optional exponent (eorE, an optional+or-, then one or more digits). Only the ASCII digits0-9count as digits.- If the number has a fraction or an exponent, return a
float. Otherwise return anint. - Forms such as
01,-,1.,.5and1eare malformed.
- If the number has a fraction or an exponent, return a
- Literals.
true,falseandnullare written in lowercase exactly. - Whole input. The text must hold exactly one value, with only whitespace around it. Leftover characters (for example
[1] 2) make the input malformed. Empty or whitespace-only input is malformed.
Errors
For any malformed input, raise ValueError. This includes trailing commas, missing colons or commas, non-string keys, unclosed containers or strings, unknown tokens, and everything listed above.
Constraints
- The input is a Python
str. - Containers may be nested, to a depth that fits within Python's normal recursion limit.
- Whitespace appears only in the places allowed by the rules above. Anything else is malformed.
- Return types must match exactly:
1is anint,1.0and1e2arefloats.
Examples
Example 1
Input: decode_json_text('{"a": 1, "b": [true, null]}')
Output: {'a': 1, 'b': [True, None]}
Example 2
Input: decode_json_text('[1, 2.5, "hello"]')
Output: [1, 2.5, 'hello']
Example 3
Input: decode_json_text('{}')
Output: {}
Example 4
Input: decode_json_text(' { "nested" : { "x" : -12, "ok" : false }, "items" : [ ] } ')
Output: {'nested': {'x': -12, 'ok': False}, 'items': []}
Hints
Hint 1
Keep one cursor into the string. Look at the first non-whitespace character of a value: `{`, `[`, `"`, `-` or a digit, or a letter, and it tells you which sub-parser to call. No backtracking is needed.
Hint 2
Write one function per grammar rule (value, object, array, string, number). Containers call the value parser for their children, which handles nesting. After each element, require either a comma or the closing bracket, and after a comma require another element.
Hint 3
Validate numbers piece by piece: optional minus, then `0` or a nonzero digit followed by digits, then an optional fraction that needs at least one digit, then an optional exponent that needs at least one digit. After parsing the top-level value, skip whitespace and check that the cursor is at the end of the input.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
JSON's grammar is small and needs only one character of lookahead, so a recursive-descent parser fits well. Keep a single cursor pos that moves left to right. At the start of any value, skip whitespace and look at the current character:
{starts an object.[starts an array."starts a string.-or a digit starts a number.t,fornstarts a literal, which is matched againsttrue,falseornull.
Each reader consumes exactly the characters of its value and leaves the cursor just past it. Objects and arrays call read_value for their children, which handles nesting.
Each reader enforces its own rules:
- Objects require a string key, then
:, then a value, then either,or}. After a comma another key is required, so{"a":1,}fails. Assigning into adictmakes the last duplicate key win. - Arrays work the same way with
,or]. After a comma another value is required, so[1,]fails because]is not a valid value. - Strings collect characters until the closing quote. A backslash must be followed by
"or\. Raw characters below0x20and a missing closing quote raiseValueError. - Numbers are scanned in stages: optional
-, then0or a nonzero digit followed by digits, then an optional fraction that needs at least one digit, then an optional exponent that needs at least one digit. The result is afloatif a fraction or exponent was seen, otherwise anint. Digits are checked against the ASCII set0-9.
After the top-level value, skip whitespace and require the cursor to be at the end. This rejects inputs such as [1] 2 and truex. Empty input fails in read_value because there is nothing to read.
Why it is correct
The first character of a value always determines which rule applies, so the parser never has to guess or backtrack. Each rule consumes precisely the text its grammar allows and raises ValueError the moment the text deviates. The final end-of-input check ensures the whole string is exactly one value. Together these accept exactly the described language and produce the matching Python values and types.
Complexity
- Time: O(n). Every character is examined a constant number of times.
- Space: O(n + d). The result takes O(n), and the recursion stack takes O(d) for nesting depth d.
Reference solution
from typing import Any
def decode_json_text(text: str) -> Any:
s = text
n = len(s)
pos = 0
digits = '0123456789'
def skip_ws():
nonlocal pos
while pos < n and s[pos] in ' \t\r\n':
pos += 1
def is_digit_at(i):
return i < n and s[i] in digits
def read_value():
nonlocal pos
skip_ws()
if pos >= n:
raise ValueError('Unexpected end of input')
ch = s[pos]
if ch == '{':
return read_object()
if ch == '[':
return read_array()
if ch == '"':
return read_string()
if s.startswith('true', pos):
pos += 4
return True
if s.startswith('false', pos):
pos += 5
return False
if s.startswith('null', pos):
pos += 4
return None
if ch == '-' or ch in digits:
return read_number()
raise ValueError('Invalid value')
def read_string():
nonlocal pos
if pos >= n or s[pos] != '"':
raise ValueError('Expected string')
pos += 1
out = []
while pos < n:
ch = s[pos]
pos += 1
if ch == '"':
return ''.join(out)
if ch == '\\':
if pos >= n or s[pos] not in '\\"':
raise ValueError('Unsupported escape sequence')
out.append(s[pos])
pos += 1
else:
if ord(ch) < 0x20:
raise ValueError('Invalid control character')
out.append(ch)
raise ValueError('Unterminated string')
def read_number():
nonlocal pos
start = pos
if s[pos] == '-':
pos += 1
if not is_digit_at(pos):
raise ValueError('Invalid number')
if s[pos] == '0':
pos += 1
if is_digit_at(pos):
raise ValueError('Invalid number')
else:
while is_digit_at(pos):
pos += 1
is_float = False
if pos < n and s[pos] == '.':
is_float = True
pos += 1
if not is_digit_at(pos):
raise ValueError('Invalid number')
while is_digit_at(pos):
pos += 1
if pos < n and s[pos] in 'eE':
is_float = True
pos += 1
if pos < n and s[pos] in '+-':
pos += 1
if not is_digit_at(pos):
raise ValueError('Invalid number')
while is_digit_at(pos):
pos += 1
token = s[start:pos]
try:
return float(token) if is_float else int(token)
except ValueError as exc:
raise ValueError('Invalid number') from exc
def read_array():
nonlocal pos
pos += 1
result = []
skip_ws()
if pos < n and s[pos] == ']':
pos += 1
return result
while True:
result.append(read_value())
skip_ws()
if pos >= n:
raise ValueError('Unterminated array')
if s[pos] == ']':
pos += 1
return result
if s[pos] != ',':
raise ValueError('Expected comma in array')
pos += 1
def read_object():
nonlocal pos
pos += 1
result = {}
skip_ws()
if pos < n and s[pos] == '}':
pos += 1
return result
while True:
skip_ws()
if pos >= n or s[pos] != '"':
raise ValueError('Expected object key')
key = read_string()
skip_ws()
if pos >= n or s[pos] != ':':
raise ValueError('Expected colon in object')
pos += 1
result[key] = read_value()
skip_ws()
if pos >= n:
raise ValueError('Unterminated object')
if s[pos] == '}':
pos += 1
return result
if s[pos] != ',':
raise ValueError('Expected comma in object')
pos += 1
value = read_value()
skip_ws()
if pos != n:
raise ValueError('Unexpected trailing characters')
return value