FrontendInterviews.dev

Loading problem…

36. JSON.stringify - Simple

Easy•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

Implement a simplified version of JSON.stringify that converts JavaScript values to JSON strings.

Given a JavaScript value, convert it to a JSON string representation. Your implementation should handle:

  • Primitives: numbers, strings, booleans, null
  • Arrays: arrays of any supported types
  • Objects: plain objects with string keys

Requirements

1. Basic Functionality

  • Convert numbers to string representation
  • Convert strings with proper escaping (quotes, backslashes, newlines, etc.)
  • Convert booleans to "true" or "false"
  • Convert null to "null"
  • Convert arrays to comma-separated values in brackets
  • Convert objects to comma-separated key-value pairs in braces

Example Usage

stringify(42);                    // "42"
stringify("hello");                // '"hello"'
stringify(true);                   // "true"
stringify(null);                   // "null"
stringify([1, 2, 3]);             // "[1,2,3]"
stringify({a: 1, b: 2});          // '{"a":1,"b":2}'

Real-World Context

This problem models real JSON serialization:

  • API responses: Convert JavaScript objects to JSON for HTTP requests
  • Data storage: Serialize data for localStorage or databases
  • Configuration files: Convert config objects to JSON format
  • Data transfer: Prepare data for network transmission

Constraints

  • 1 <= input complexity <= 100
  • Handle numbers, strings, booleans, null
  • Handle arrays and objects
  • Properly escape special characters in strings
  • Handle nested structures up to 3 levels
  • Do not handle undefined, functions, or circular references