KatInterview

Build a Recursive-Descent Decoder for a JSON Subset

StringsAuto-graded · 20 test cases
HardAuto-gradedStringsparsingrecursive-descentstrings

Last 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

JSONPython result
object { ... }dict
array [ ... ]list
string "..."str
numberint or float
true / falseTrue / False
nullNone

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" : value members 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 below 0x20 inside a string is malformed. A string that never closes is malformed.
  • Numbers. A number follows the usual JSON grammar: an optional -, then either a single 0 or a nonzero digit followed by more digits, then an optional fraction (. followed by one or more digits), then an optional exponent (e or E, an optional + or -, then one or more digits). Only the ASCII digits 0-9 count as digits.
    • If the number has a fraction or an exponent, return a float. Otherwise return an int.
    • Forms such as 01, -, 1., .5 and 1e are malformed.
  • Literals. true, false and null are 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: 1 is an int, 1.0 and 1e2 are floats.

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.