Skip to content
Onsite

JSON.parse Implementation

HardP3Coding

Implement parse(text), a version of JSON.parse with no reviver. Do not call JSON.parse, eval or new Function.

Accept exactly the JSON grammar and throw a SyntaxError for anything else:

  • Values: objects, arrays, strings, numbers, true, false, null. Whitespace (space, tab, newline, carriage return) is allowed between tokens and around the whole document.
  • Strings use double quotes only. The allowed escapes are backslash followed by one of " \ / b f n r t, and \uXXXX (exactly four hex digits). Raw control characters (below U+0020) inside a string are an error, as is any other escape.
  • Numbers: optional -, an integer part with no leading zeros (0 alone is fine), optional fraction (. followed by digits), optional exponent. +1, 01, 1., .5, NaN and Infinity are errors.
  • No trailing commas, no comments, no single quotes, no unquoted keys, nothing but whitespace after the value. Empty input is an error.
  • Duplicate keys: the last one wins. A key named "__proto__" must become an ordinary own property and must not change the object's prototype.

Example 1

Input
parse('{"a":[1,2,{"b":null}],"c":"x"}')
Output
{ a: [1, 2, { b: null }], c: 'x' }

Constraints

  • 0 <= text.length <= 10^5
  • Nesting depth <= 1000

Hints

Run checks the 3 visible tests, Submit all 14.