← JavaScript Coding

JSON.stringify II (Advanced)

hard
Asked at
Google
Snap
Google, Snap

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 -Infinity should become 'null'.
  • Functions/Symbols/Undefined: Should be omitted in objects, or become 'null' in arrays. Return undefined if 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.

Premium

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
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

JS CodingMedium

86. API Retry

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Google interview
  • Snap interview