Skip to the solution
HardDSAAsked in 20249 min read

JSON.stringify Polyfill

4.1k views

The problem

Problem, as an interviewer would state it: "Implement a basic version of JSON.stringify. Discuss edge cases, runtime, and alternatives."

Examples:

Code
jsonStringify({ a: 1, b: undefined, c: [undefined, NaN, new Date(0)] });   // '{"a":1,"c":[null,null,"1970-01-01T00:00:00.000Z"]}'
jsonStringify({ a: [1, { b: 2 }] }, null, 2);                              // pretty-printed with 2 spaces
jsonStringify(circular);                                                    // throws TypeError

Clarifying questions expected:

  • How much of the contract: toJSON, the replacer function and array, space?
  • What happens to undefined, functions, symbols, NaN, BigInt and circular structures?
  • Which keys are included, and in what order?

Code / implementation expected: Yes — real code, checked against the native JSON.stringify on many inputs.

  • polyfill
  • recursion

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

9 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 polyfill matches the native JSON.stringify on random values, replacers and spaces, on every UTF-16 code unit, and prints each rule

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 126 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

DOM select elements custom selector

Continue