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. The result is a JSON object format without outer quotes.

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 String INPUT value "hello" Type: String Input Value: "hello" Constraint: Cannot use built-in JSON.stringify() ALGORITHM STEPS 1 Check Type Identify value type 2 String Handler Add escape quotes 3 Wrap in Quotes \"value\" format 4 Return Result JSON string output Recursive Approach - string: add quotes - number: toString - array: recurse [] - object: recurse {} FINAL RESULT JSON String Output: "\"hello\"" Breakdown: " outer quote \ escape char " inner quote hello content Status: OK Valid JSON String Key Insight: The recursive approach handles each type differently: strings need escaped quotes (\"), numbers convert directly, arrays/objects recursively process their elements. For input "hello", we wrap in quotes and escape: "hello" becomes "\"hello\"" TutorialsPoint - Convert Object to JSON String | Recursive Approach
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