Proper way to catch exception from JSON.parse

JSONFront End TechnologyObject Oriented Programming

The best way to catch invalid JSON parsing errors is to put the calls to JSON.parse() to a try/catch block.

Example

function parseJSONSafely(str) {
   try {
      return JSON.parse(str);
   }
   catch (e) {
      console.err(e);
      // Return a default object, or null based on use case.
      return {}
   }
}
raja
Published on 02-Dec-2019 06:09:17
Advertisements