Problem
Given a value, return a valid JSON string of that value. The value can be a string, number, array, object, boolean, or null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by Object.keys()
.
Please solve it without using the built-in JSON.stringify
method.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Constraints:
value
is a valid JSON value1 <= JSON.stringify(object).length <= 10^5
maxNestingLevel <= 1000
- all strings contain only alphanumeric characters
Solution
Method 1 – Recursive Serialization 1
Intuition
To convert a value to a JSON string without using JSON.stringify
, we recursively process the value based on its type. Strings are quoted, arrays and objects are traversed recursively, and primitives are converted to their string representation. Key order for objects is preserved using Object.keys()
.
Approach
- If the value is null, return ’null'.
- If the value is a string, return the value wrapped in double quotes.
- If the value is a number or boolean, return its string representation.
- If the value is an array, recursively serialize each element and join with commas, wrapping the result in square brackets.
- If the value is an object, for each key in
Object.keys(obj)
, serialize the key and value, join pairs with commas, and wrap in curly braces. - Return the resulting string.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the total number of characters in the output string, as each value is processed once. - 🧺 Space complexity:
O(n)
, for the recursion stack and the resulting string.