FrontendPro

35Implement JSON.stringify() for common data types and edge cases

mediumAbout 35 minutesCodingrecursionstringsjson

Problem

Implement stringify(value) so that it returns exactly what JSON.stringify(value) returns, without calling JSON.stringify. You do not need to support the replacer and space arguments.

stringify({ name: "Asha", tags: ["a", "b"], age: undefined }); // '{"name":"Asha","tags":["a","b"]}'
stringify([undefined, () => {}, NaN]); // "[null,null,null]"
stringify(new Date(0)); // '"1970-01-01T00:00:00.000Z"'
stringify(undefined); // undefined

Requirements

  • Strings are quoted and escaped: ", \, and control characters such as new lines and tabs.
  • NaN, Infinity and -Infinity become null.
  • undefined, functions and symbols are skipped in objects, become null in arrays, and make the top-level result undefined.
  • Call toJSON() when a value has one (this is how Date works), passing the key.
  • Unwrap boxed primitives such as new String("x").
  • Throw a TypeError for circular references and for BigInt values.
  • Map and Set become {}, like the built-in, because they have no own enumerable keys.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

The built-in works on a "holder" object and a key, so that toJSON(key) gets the key. Start with serialize({ "": value }, ""), exactly like the spec.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 5 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever