Overview
Turn objects into JSON text and back, and keep your page running when a server sends something that isn't valid JSON.
- JSON.stringify turns a value into text
- JSON.parse turns text into a value
- try/catch handles the error JSON.parse throws
Short Course
JSON.stringify turns a value into text; JSON.parse turns text back into a
value. Trap: JSON.parse throws on bad text and stops your code, so wrap
it in try/catch.
const text = JSON.stringify({ id: 1, ok: true }); // '{"id":1,"ok":true}'
JSON.parse(text).ok; // true
try {
JSON.parse("{bad");
} catch (err) {
console.log(err.name); // SyntaxError
}
Task
Write safeParse(text) that returns the parsed value, or null when the text
isn't valid JSON, for example safeParse("{oops") returns null.
Test Suites
Pending
Next
Output