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.
function jsonParse(text) {
// returns the parsed value; throws SyntaxError on invalid JSON.
}
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)
true/false/null. Objects and arrays nest values recursively.\", \\, \/, \n, \t, \r, \b, \f, and \uXXXX.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.