JSON.stringify II (Advanced)
Problem statement
Implement a full-featured jsonStringify function that behaves exactly like JSON.stringify() for any data type.
Advanced Requirements
- Cyclic References: Throw
TypeError('Converting circular structure to JSON'). - BigInt: Throw
TypeError('Do not know how to serialize a BigInt'). - Special Values:
NaN,Infinity, and-Infinityshould become'null'. - Functions/Symbols/Undefined: Should be omitted in objects, or become
'null'in arrays. Returnundefinedif passed as the top-level value. - toJSON: If an object has a
toJSON()method, use its return value instead. - Escaping: Correcty handle double quotes and backslashes in strings.
Example
const obj = { a: 1 };
obj.self = obj;
jsonStringify(obj); // Throws TypeError
How to approach JSON.stringify II (Advanced)
The strategy an interviewer expects you to reach for.
Advanced stringify adds the real browser rules: escapes, ignored keys, and array holes becoming null. Naive move Reuse the basic version. Then "a\nb", symbols, functions, NaN, and circular structures all misbehave. Where it breaks Control characters must escape. Functions/symbols are omitted in objects but become null in arrays. NaN/Infinity become null. Cycles should throw (or be guarded). The fix Centralize string escaping. Branch carefully for array vs object omission rules. Normalize non-finite numbers to null. Keep the recursive emitter pure. Remember: Omission rules differ for arrays vs objects — that asymmetry is the interview. Say this in the interview: I'd escape strings properly, map non-finite numbers to null, and apply different ignore-vs-null rules for functions/symbols in objects versus arrays.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.