JSON is the text format for data on the web: objects, arrays, strings, numbers, booleans, and null, with double-quoted keys. JSON.stringify(value) turns a value into that text; JSON.stringify(value, null, 2) pretty-prints it. JSON.parse(text) turns text back into a value, and throws a SyntaxError if the text is not valid JSON.
Things that are not JSON get dropped or changed by stringify: functions and undefined disappear, dates become strings. A round trip through JSON is also the quick way to deep-copy plain data.
const text = JSON.stringify({ name: "Ada", tags: ["math"] });
console.log(text); // {"name":"Ada","tags":["math"]}
const back = JSON.parse(text);
console.log(back.tags[0]); // mathYour task
Write toJson(obj) returning the compact JSON text of an object, parseConfig(text) returning the parsed object or null when the text is not valid JSON (use try/catch), and deepCopy(value) returning an independent copy of plain data.
Hint 1
try { return JSON.parse(text); } catch (e) { return null; }
Hint 2
JSON.parse(JSON.stringify(value))
Show the solution
function toJson(obj) {
return JSON.stringify(obj);
}
function parseConfig(text) {
try {
return JSON.parse(text);
} catch (e) {
return null;
}
}
function deepCopy(value) {
return JSON.parse(JSON.stringify(value));
}