call(back)
Algorithms & Data StructureshardSign in to star problems

JSON Parser

Parse a JSON document into native values without using the built-in parser: objects, arrays, strings with the standard escapes (\", \\, \/, \b, \f, \n, \r, \t, \uXXXX), numbers (negative, fractional, exponent), true, false and null, with whitespace anywhere JSON allows it. Throw on invalid input, including trailing characters.

parseJson('{"a": [1, 2.5, -3e2, true, null], "b": {"c": "d\\n"}}')
  ->  { a: [1, 2.5, -300, true, null], b: { c: "d\n" } }

The grader disables the built-in parser while your function runs, and records "invalid" when it throws.

Hints

Hint 1

Keep one index into the text. value() skips whitespace, looks at the next character and dispatches: { object, [ array, " string, t/f/n literal, otherwise number.

Hint 2

Arrays and objects are loops: read a value (or key, colon, value), then expect a comma to continue or the closing bracket to stop. A trailing comma is an error because a value must follow it.

Hint 3

After the top-level value, skip whitespace and require the end of the text.

Asked at