Open this example in the interactive library
Source code
const read = (text, fallback) => {
try {
return JSON.parse(text);
} catch (error) {
if (!(error instanceof SyntaxError)) throw error;
return fallback;
}
};
console.log(read("{bad", {}), read('{"id":7}', {}));
Sample output
{} { id: 7 }