All questions

JSON.parse

Premium

JSON.parse

JSON.parse turns a JSON string into the JavaScript value it describes. Under the hood it's a recursive-descent parser: a set of small functions, one per grammar rule, that read the text left to right and call each other to handle nesting. It's the counterpart to JSON.stringify, and building it is the classic way to learn how parsers work.

Implement jsonParse(text). Read the string with a single moving cursor and produce the corresponding value — objects, arrays, strings (with escapes), numbers, and the literals true/false/null — ignoring insignificant whitespace. Throw a SyntaxError on malformed input.

Signature

function jsonParse(text) {
  // returns the parsed value; throws SyntaxError on invalid JSON.
}

Examples

jsonParse('{"a": 1, "b": [2, 3]}'); // { a: 1, b: [2, 3] }
jsonParse('[true, null, "hi"]');     // [true, null, 'hi']
jsonParse('-1.5e2');                 // -150
jsonParse('"a\\nb"');   // 'a\nb'  — escape decoded
jsonParse('{}x');       // throws SyntaxError (trailing characters)

Notes

  • The JSON grammar — a value is an object, array, string, number, or one of true/false/null. Objects and arrays nest values recursively.
  • One cursor — keep a single index into the string; each parse function consumes the characters it recognizes and leaves the cursor just past them.
  • Strings need escapes — handle \", \\, \/, \n, \t, \r, \b, \f, and \uXXXX.
  • Numbers — support an optional sign, a fractional part, and an exponent.
  • Whitespace — spaces, tabs, and newlines between tokens are insignificant; skip them.
  • Errors — malformed input (bad token, missing comma, unterminated string, trailing characters) must throw a SyntaxError, not return a partial result.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium