Convert Object to JSON String Problem
#2633
Description
LeetCode Problem 2633.
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.
Example 1:
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:
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:
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:
Input: object = true
Output: true
Explanation:
Primitive types are valid inputs.
Constraints:
valueis a valid JSON value1 <= JSON.stringify(object).length <= 10^5maxNestingLevel <= 1000- all strings contain only alphanumeric characters
Solution
Approach: Recursive serializer
Branch on the type of the value:
null, booleans and numbers:String(value)givesnull,true,-12, ...- strings: wrap in double quotes (the problem promises alphanumeric strings, so no escaping is needed).
- arrays: serialize each element, join with
,, wrap in[]. Empty arrays give[]. - objects: for each key from
Object.keys, output"key":followed by the serialized value, join with,, wrap in{}.
Check null before the generic object case, since typeof null is "object", and check Array.isArray before plain objects.
Complexity: O(L) time for output length L (joining built strings); recursion depth up to the nesting level.
/**
* @param {null|boolean|number|string|Array|Object} object
* @return {string}
*/
var jsonStringify = function (object) {
if (object === null) return 'null';
if (typeof object === 'string') return '"' + object + '"';
if (typeof object !== 'object') return String(object);
if (Array.isArray(object)) {
return '[' + object.map(jsonStringify).join(',') + ']';
}
const parts = Object.keys(object).map((key) => '"' + key + '":' + jsonStringify(object[key]));
return '{' + parts.join(',') + '}';
};