Dev Helpers
← Back

Decode JSON with a fallback for malformed input

Decode JSON with a fallback for malformed input in JavaScript.

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 }