#2633
Medium JavaScript Convert object to json string
78.0% acceptance
Mar 31, 2026
209
12
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.
Solution
TypeScript
Time O(1)
Space O(1)
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
function jsonStringify(object: JSONValue): string {
if (object === null) return 'null';
if (typeof object === 'boolean') return String(object);
if (typeof object === 'number') return String(object);
if (typeof object === 'string') return '"' + object + '"';
if (Array.isArray(object)) {
return '[' + object.map(jsonStringify).join(',') + ']';
}
const entries = Object.keys(object).map(key => '"' + key + '"' + ':' + jsonStringify(object[key]));
return '{' + entries.join(',') + '}';
};