Convert Object to JSON String - Problem

Given a value, return a valid JSON string representation of that value. The value can be a string, number, array, object, boolean, or null.

The returned string should not include extra spaces and the order of keys should be the same as the order returned by Object.keys().

Important: You cannot use the built-in JSON.stringify method.

Input & Output

Example 1 — Basic String
$ Input: value = "hello"
Output: "\"hello\""
💡 Note: String values need to be wrapped in quotes and escaped properly
Example 2 — Simple Array
$ Input: value = [1, 2, 3]
Output: [1,2,3]
💡 Note: Array elements are converted recursively and joined with commas, no spaces
Example 3 — Object with Mixed Types
$ Input: value = {"name": "John", "age": 30, "active": true}
Output: "{\"name\":\"John\",\"age\":30,\"active\":true}"
💡 Note: Object keys and values are converted recursively, maintaining key order

Constraints

  • The value can be any valid JavaScript data type
  • Objects will have at most 1000 keys
  • Arrays will have at most 1000 elements
  • Maximum nesting depth is 100 levels
  • String values will not exceed 10000 characters

Visualization

Tap to expand
Convert Object to JSON StringJavaScript ValueObjects: {a: 1}Arrays: [1, 2, 3]Strings: "hello"Numbers: 42Booleans: trueJSON FormattingAdd quotes to stringsEscape special charsHandle nestingNo extra spacesKey order preservedJSON String"{\"a\":1}""[1,2,3]""\"hello\"""42""true"Key Challenge: Handle all JavaScript types without JSON.stringify()❌ Cannot use JSON.stringify() - must implement manually✅ Use recursion to handle nested objects and arrays
Understanding the Visualization
1
Input
JavaScript value of any type (string, number, array, object, etc.)
2
Process
Apply JSON formatting rules recursively
3
Output
Valid JSON string representation
Key Takeaway
🎯 Key Insight: Recursion naturally mirrors the nested structure of JSON data
Asked in
Google 25 Meta 20 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen