Skip to the solution
HardDSAAsked in 202410 min read

JSON.parse Polyfill

1.7k views

The problem

Problem, as an interviewer would state it: "Implement a secure polyfill for JSON.parse using a recursive descent parsing approach, validating characters to prevent arbitrary script execution. Discuss edge cases, runtime, and alternatives."

Examples:

Code
jsonParse('{"a":[1,2.5,-3e2,true,null],"b":{"c":"x\\ny"}}');   // { a: [1, 2.5, -300, true, null], b: { c: "x\ny" } }
jsonParse('{"a":1,}');                                       // throws SyntaxError (trailing comma)
jsonParse('{"n":"2026-01-15T10:30:00.000Z"}', (k, v) => (k === "n" ? new Date(v) : v));   // reviver support

Clarifying questions expected:

  • How strict must it be (trailing commas, single quotes, comments, leading zeros, NaN)?
  • Which error should it throw, and must the optional reviver be supported?
  • How should __proto__ keys, duplicate keys and very deep nesting behave?

Code / implementation expected: Yes — a real parser, checked against the native JSON.parse on many inputs.

  • polyfill
  • object
  • string

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the parser rejects and accepts exactly like the native JSON.parse on exhaustive, code-unit and random inputs, never evaluates text, and keeps __proto__ a plain key

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 138 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Safely Merge Untrusted Input Into an Object Without a Prototype-Pollution Vulnerability

Continue