FrontendInterviews.dev

Loading problem…

38. JSON.stringify - Complex

Hard•
Acceptance: 80.00%
•
🔓3/3 Pro unlocks today

Implement a more complete version of JSON.stringify that handles advanced cases including:

  • Nested objects and arrays (deep nesting)
  • Special string characters (quotes, backslashes, control characters)
  • Numbers (integers, floats, negative, zero)
  • Mixed data types in arrays and objects
  • Empty structures
  • Complex nested structures

Given a JavaScript value, convert it to a JSON string representation. Your implementation should handle all basic types and complex nested structures.

Requirements

1. Advanced Functionality

  • Handle deeply nested structures (5+ levels)
  • Properly escape all special characters in strings
  • Handle edge cases: empty strings, zero, negative numbers
  • Preserve order of object keys
  • Handle mixed types in arrays
  • Handle objects with numeric and string keys

Example Usage

stringify({a: {b: {c: {d: {e: 1}}}}});  // Deep nesting
stringify('text with "quotes"');         // Escaped quotes
stringify([1, "two", true, null]);      // Mixed types
stringify({0: "zero", 1: "one"});       // Numeric keys

Real-World Context

This problem models real JSON serialization in production:

  • Complex API payloads: Serialize nested data structures
  • Configuration serialization: Convert complex config objects
  • Data persistence: Save complex application state
  • Cross-system communication: Prepare data for different systems

Constraints

  • 1 <= input complexity <= 1000
  • Handle nested structures up to 10 levels
  • Properly escape all special characters
  • Handle all number types (int, float, negative, zero)
  • Preserve object key order
  • Handle arrays with mixed types