Proper way to catch exception from JSON.parse


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 {}
   }
}

Updated on: 02-Dec-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements