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:

1
2
3
4
5
Input: object = {"y":1,"x":2}
Output: {"y":1,"x":2}
Explanation: 
Return the JSON representation.
Note that the order of keys should be the same as the order returned by Object.keys().

Example 2:

1
2
3
4
Input: object = {"a":"str","b":-12,"c":true,"d":null}
Output: {"a":"str","b":-12,"c":true,"d":null}
Explanation:
The primitives of JSON are strings, numbers, booleans, and null.

Example 3:

1
2
3
4
Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}}
Output: {"key":{"a":1,"b":[{},null,"Hello"]}}
Explanation:
Objects and arrays can include other objects and arrays.

Example 4:

1
2
3
4
Input: object = true
Output: true
Explanation:
Primitive types are valid inputs.

Constraints:

  • value is a valid JSON value
  • 1 <= 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

  1. If the value is null, return ’null'.
  2. If the value is a string, return the value wrapped in double quotes.
  3. If the value is a number or boolean, return its string representation.
  4. If the value is an array, recursively serialize each element and join with commas, wrapping the result in square brackets.
  5. 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.
  6. Return the resulting string.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    stringify(val) {
        if (val === null) return 'null';
        if (typeof val === 'string') return '"' + val + '"';
        if (typeof val === 'number' || typeof val === 'boolean') return String(val);
        if (Array.isArray(val)) {
            let ans = val.map(v => this.stringify(v)).join(',');
            return '[' + ans + ']';
        }
        if (typeof val === 'object') {
            let ans = Object.keys(val).map(k => '"' + k + '":' + this.stringify(val[k])).join(',');
            return '{' + ans + '}';
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    stringify(val: any): string {
        if (val === null) return 'null';
        if (typeof val === 'string') return '"' + val + '"';
        if (typeof val === 'number' || typeof val === 'boolean') return String(val);
        if (Array.isArray(val)) {
            const ans = val.map(v => this.stringify(v)).join(',');
            return '[' + ans + ']';
        }
        if (typeof val === 'object') {
            const ans = Object.keys(val).map(k => '"' + k + '":' + this.stringify(val[k])).join(',');
            return '{' + ans + '}';
        }
    }
}

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.