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); // undefinedRequirements
- Strings are quoted and escaped:
",\, and control characters such as new lines and tabs. NaN,Infinityand-Infinitybecomenull.undefined, functions and symbols are skipped in objects, becomenullin arrays, and make the top-level resultundefined.- Call
toJSON()when a value has one (this is howDateworks), passing the key. - Unwrap boxed primitives such as
new String("x"). - Throw a
TypeErrorfor circular references and forBigIntvalues. MapandSetbecome{}, 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.