Overview
Implement jsonStringify(value) that serializes a value to a JSON string.
Constraints
- Handle: strings, numbers, booleans, null, arrays, plain objects
- Do not use
JSON.stringify - Strings must be double-quoted
Examples
jsonStringify({ a: 1, b: 'hello' }); // '{"a":1,"b":"hello"}'
jsonStringify([1, null, true]); // '[1,null,true]'Solution
Reveal solution
function jsonStringify(value) {
if (value === null) return 'null';
if (typeof value === 'boolean') return value ? 'true' : 'false';
if (typeof value === 'number') return String(value);
if (typeof value === 'string') return '"' + value.replace(/\\/g,'\\\\').replace(/"/g,'\\"') + '"';
if (Array.isArray(value)) return '[' + value.map(v => jsonStringify(v)).join(',') + ']';
if (typeof value === 'object') {
const pairs = Object.keys(value).map(k => jsonStringify(k) + ':' + jsonStringify(value[k]));
return '{' + pairs.join(',') + '}';
}
return undefined;
}json-stringify.js
JSON Stringify
mediumcodingJavaScriptRecursion
Overview
Implement jsonStringify(value) that serializes a value to a JSON string.
Constraints
- Handle: strings, numbers, booleans, null, arrays, plain objects
- Do not use
JSON.stringify - Strings must be double-quoted
Examples
jsonStringify({ a: 1, b: 'hello' }); // '{"a":1,"b":"hello"}'
jsonStringify([1, null, true]); // '[1,null,true]'Solution
Reveal solution
function jsonStringify(value) {
if (value === null) return 'null';
if (typeof value === 'boolean') return value ? 'true' : 'false';
if (typeof value === 'number') return String(value);
if (typeof value === 'string') return '"' + value.replace(/\\/g,'\\\\').replace(/"/g,'\\"') + '"';
if (Array.isArray(value)) return '[' + value.map(v => jsonStringify(v)).join(',') + ']';
if (typeof value === 'object') {
const pairs = Object.keys(value).map(k => jsonStringify(k) + ':' + jsonStringify(value[k]));
return '{' + pairs.join(',') + '}';
}
return undefined;
}NameTopicDifficulty
103 of 103 problems