JSON.stringify
JavaScript
medium
25 mins
Implement a custom version of JSON.stringify. This function should serialize a JavaScript object or value into a JSON string. The implementation should mimic the behavior of the native JSON.stringify, including handling of:
- Primitives (
string,number,boolean,null) - Arrays and nested arrays
- Plain objects with nested properties
- Functions and
undefined(ignored in objects, replaced withnullin arrays)
Example Inputs & Outputs
JSONStringify("hello") // → '"hello"' JSONStringify({ name: "Alice", age: 30 }) // → '{"name":"Alice","age":30}' JSONStringify([1, "a", true, null]) // → '[1,"a",true,null]' JSONStringify({ a: undefined, b: function() {}, c: 5 }) // → '{"c":5}' JSONStringify([undefined, function() {}, 5]) // → '[null,null,5]'
Constraints & Edge Cases
- Should handle all basic types: string, number, boolean, null, object, array
- Functions and
undefined:- Omitted in objects
- Converted to
nullin arrays
- Throws
TypeErroron circular references - Does not handle special objects like
Date,Set,Map, etc.
Companies:
adobe
stripe
paytm
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
