Recurse on the value's type: null, booleans and finite numbers print as themselves, NaN and Infinity print null, strings are quoted with escapes, arrays print every element (with undefined, functions and symbols becoming null), and objects print their own enumerable string keys, leaving those values out. The details interviewers check are the spec's order of operations for each property: call toJSON (that's how Date becomes a string), then the replacer with the holder as this, then unwrap Number/String/Boolean objects. Throw a TypeError on cycles and BigInt, honour space (capped at 10), and escape lone surrogates.
Implement JSON.stringify().
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
One branch per type. The rule worth saying out loud: values JSON has no form for (undefined, functions, symbols) are left out of objects but become null in arrays, so array positions don't shift. NaN and ±Infinity become null too. Strings escape ", \ and control characters, with short forms like \n where JSON has them.
function stringify(value) {if (value === null) return 'null';if (typeof value === 'boolean') return String(value);if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'null'; // NaN, Infinity -> nullif (typeof value === 'string') return quote(value);if (Array.isArray(value)) {// In arrays, values JSON can't hold become null, so positions are kept.return '[' + value.map((v) => stringify(v) ?? 'null').join(',') + ']';}if (typeof value === 'object') {const parts = [];for (const key of Object.keys(value)) {const s = stringify(value[key]);if (s !== undefined) parts.push(quote(key) + ':' + s); // in objects, they are left out}return '{' + parts.join(',') + '}';}return undefined; // undefined, functions and symbols have no JSON form}function quote(s) {const named = { '"': '\\"', '\\': '\\\\', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\b': '\\b', '\f': '\\f' };return '"' + s.replace(/["\\\u0000-\u001f]/g, (c) => named[c] ?? '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')) + '"';}
passes 5 checks run on every build, against the native method where there is one
- primitives, like native
- NaN and Infinity become null
- nested objects and arrays
- undefined, functions and symbols: left out of objects, null in arrays
- strings are escaped
The spec wraps the value in a holder { "": value } and serialises each property in a fixed order: toJSON(key) if the value has one (Date.prototype.toJSON returns the ISO string), then the replacer function called as replacer.call(holder, key, value), then unwrapping of new Number/new String/new Boolean. A replacer array is a list of keys to keep, in that order, applied to objects but not arrays. A stack of objects currently being serialised detects cycles: seeing one again throws a TypeError, but the same object in two places isn't a cycle. BigInt throws unless something gives it a toJSON.
// The spec's QuoteJSONString: short escapes, \u00XX for other control characters, and lone// surrogates escaped as \uDXXX (well-formed JSON.stringify, ES2019).function quote(s) {const named = { 0x22: '\\"', 0x5c: '\\\\', 0x08: '\\b', 0x0c: '\\f', 0x0a: '\\n', 0x0d: '\\r', 0x09: '\\t' };let out = '"';for (let i = 0; i < s.length; i++) {const c = s.charCodeAt(i);if (named[c]) out += named[c];else if (c < 0x20) out += '\\u' + c.toString(16).padStart(4, '0');else if (c >= 0xd800 && c <= 0xdfff) {const next = s.charCodeAt(i + 1);if (c <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {out += s[i] + s[i + 1]; // a proper pair: one character, kept as it isi++;} else out += '\\u' + c.toString(16);} else out += s[i];}return out + '"';}function stringify(value, replacer) {const replacerFn = typeof replacer === 'function' ? replacer : undefined;const allow = Array.isArray(replacer) ? [...new Set(replacer.filter((k) => typeof k === 'string' || typeof k === 'number').map(String))] : undefined;const stack = []; // objects being serialised right now: seeing one again is a cycle// Serialise holder[key]: the spec's SerializeJSONProperty.function property(holder, key) {let value = holder[key];// toJSON first (Date has one), then the replacer, called with the holder as `this`.if (value !== null && (typeof value === 'object' || typeof value === 'bigint') && typeof value.toJSON === 'function') {value = value.toJSON(key);}if (replacerFn) value = replacerFn.call(holder, key, value);// Wrapper objects stand for their primitive.if (value instanceof Number) value = Number(value);else if (value instanceof String) value = String(value);else if (value instanceof Boolean) value = value.valueOf();if (value === null) return 'null';if (typeof value === 'boolean') return String(value);if (typeof value === 'string') return quote(value);if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'null';if (typeof value === 'bigint') throw new TypeError('Do not know how to serialize a BigInt');if (typeof value === 'object') return Array.isArray(value) ? array(value) : object(value);return undefined;}function enter(value) {if (stack.includes(value)) throw new TypeError('Converting circular structure to JSON');stack.push(value);}function object(obj) {enter(obj);const parts = [];for (const key of allow ?? Object.keys(obj)) {const s = property(obj, key);if (s !== undefined) parts.push(quote(key) + ':' + s);}stack.pop();return '{' + parts.join(',') + '}';}function array(arr) {enter(arr);const parts = [];for (let i = 0; i < arr.length; i++) parts.push(property(arr, String(i)) ?? 'null');stack.pop();return '[' + parts.join(',') + ']';}// The spec wraps the value in a holder so toJSON and the replacer see key "".return property({ '': value }, '');}
passes 7 checks run on every build, against the native method where there is one
- Date and custom toJSON
- toJSON receives its key
- wrapper objects stand for their primitive
- BigInt and cycles throw a TypeError, like native
- a shared object that isn't a cycle is fine
- replacer function: called with the holder as this, can drop and change values
- replacer array: only these keys, in this order, objects only
space is a number of spaces (clamped to 0–10) or the first 10 characters of a string; with a gap, each item goes on its own line, : gets a space, and empty {}/[] stay on one line. Since ES2019 a lone surrogate (\ud800) is escaped as \ud800 so the output is valid UTF-8; proper pairs stay as one character. String(-0) is "0", Object.keys already gives the required key order (integer keys first), and symbol keys never appear. The last check compares with the native JSON.stringify on 300 random values.
// The spec's QuoteJSONString: short escapes, \u00XX for other control characters, and lone// surrogates escaped as \uDXXX (well-formed JSON.stringify, ES2019).function quote(s) {const named = { 0x22: '\\"', 0x5c: '\\\\', 0x08: '\\b', 0x0c: '\\f', 0x0a: '\\n', 0x0d: '\\r', 0x09: '\\t' };let out = '"';for (let i = 0; i < s.length; i++) {const c = s.charCodeAt(i);if (named[c]) out += named[c];else if (c < 0x20) out += '\\u' + c.toString(16).padStart(4, '0');else if (c >= 0xd800 && c <= 0xdfff) {const next = s.charCodeAt(i + 1);if (c <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {out += s[i] + s[i + 1]; // a proper pair: one character, kept as it isi++;} else out += '\\u' + c.toString(16);} else out += s[i];}return out + '"';}function stringify(value, replacer, space) {const replacerFn = typeof replacer === 'function' ? replacer : undefined;let allow;if (Array.isArray(replacer)) {allow = [];for (const k of replacer) {const item = typeof k === 'string' ? k : typeof k === 'number' || k instanceof Number || k instanceof String ? String(k) : undefined;if (item !== undefined && !allow.includes(item)) allow.push(item);}}// Indentation: a number of spaces (at most 10) or the first 10 characters of a string.if (space instanceof Number) space = Number(space);else if (space instanceof String) space = String(space);const gap = typeof space === 'number' ? ' '.repeat(Math.min(10, Math.max(0, Math.trunc(space) || 0))) : typeof space === 'string' ? space.slice(0, 10) : '';const stack = [];function property(holder, key, indent) {let value = holder[key];if (value !== null && (typeof value === 'object' || typeof value === 'bigint') && typeof value.toJSON === 'function') {value = value.toJSON(key);}if (replacerFn) value = replacerFn.call(holder, key, value);if (value instanceof Number) value = Number(value);else if (value instanceof String) value = String(value);else if (value instanceof Boolean) value = value.valueOf();else if (value instanceof BigInt) value = value.valueOf();if (value === null) return 'null';if (typeof value === 'boolean') return String(value);if (typeof value === 'string') return quote(value);if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'null'; // String(-0) is "0"if (typeof value === 'bigint') throw new TypeError('Do not know how to serialize a BigInt');if (typeof value === 'object') return Array.isArray(value) ? array(value, indent) : object(value, indent);return undefined;}function enter(value) {if (stack.includes(value)) throw new TypeError('Converting circular structure to JSON');stack.push(value);}// With a gap: one item per line, indented one step deeper than the bracket.function wrap(open, parts, close, indent, inner) {if (parts.length === 0) return open + close;if (!gap) return open + parts.join(',') + close;return open + '\n' + inner + parts.join(',\n' + inner) + '\n' + indent + close;}function object(obj, indent) {enter(obj);const inner = indent + gap;const parts = [];// Object.keys gives the spec's order: integer keys ascending, then strings in insertion order.// Symbol keys are never included.for (const key of allow ?? Object.keys(obj)) {const s = property(obj, key, inner);if (s !== undefined) parts.push(quote(key) + (gap ? ': ' : ':') + s);}stack.pop();return wrap('{', parts, '}', indent, inner);}function array(arr, indent) {enter(arr);const inner = indent + gap;const parts = [];for (let i = 0; i < arr.length; i++) parts.push(property(arr, String(i), inner) ?? 'null');stack.pop();return wrap('[', parts, ']', indent, inner);}return property({ '': value }, '', '');}
passes 6 checks run on every build, against the native method where there is one
- indentation with a number or a string, like native
- indentation is capped at 10
- lone surrogates are escaped; proper pairs are kept
- -0 is "0", key order is integers first, symbol keys are skipped
- BigInt with a toJSON is allowed, like native
- matches native on 300 random values
Dates arrive as strings
JSON.stringify({ at: new Date() }) gives an ISO string because of Date.prototype.toJSON, and JSON.parse doesn't turn it back. APIs and caches that round-trip through JSON hand back strings, which is a common cause of date.getTime is not a function.
Keeping secrets out of logs
A replacer that returns undefined for keys like password or token strips them from anything you serialise for logging or analytics, without changing the object.
BigInt IDs
IDs larger than Number.MAX_SAFE_INTEGER arrive as BigInt in some clients, and JSON.stringify throws on them. The usual fixes are sending IDs as strings or a replacer that converts bigint values.
Leaving
undefinedout of arrays instead of writingnull, which shifts every later element.Printing
NaNorInfinityas is: that isn't valid JSON.Calling the replacer before
toJSON, or without the holder asthis.Detecting cycles with a
Setof every object ever seen, which wrongly rejects shared, non-circular references.Escaping with
JSON.stringifyitself inside the solution.Using
for...in, which also walks inherited enumerable keys.
How would you make it handle cycles instead of throwing?
Replace a repeated object with a marker such as "[Circular]", or with a path reference ({ "$ref": "$.a.b" }) that a matching parser can resolve. Track the path while recursing to build it.
Why are integer-like keys printed first?
Because Object.keys (the spec's EnumerableOwnProperties) lists array-index keys in ascending numeric order before other string keys, which keep insertion order.
What does JSON.parse's reviver do?
It's the mirror of the replacer: called bottom-up for every key with the holder as this, and whatever it returns replaces the value (returning undefined deletes it). It's where you'd turn ISO strings back into Dates.
- tc39.es/ecma262/#sec-json.stringify
- tc39.es/ecma262/#sec-serializejsonproperty
- tc39.es/ecma262/#sec-quotejsonstring
- github.com/tc39/proposal-well-formed-stringify
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON