How to validate JSON in javascript

Learn how to validate JSON in javascript.

JSON is the most widely used data format to share data over the internet and is passed around as a string.

Also known as javascript object notation. It uses Javascript’s object syntax to store data.

So it is very necessary to check if the string that we get or have is valid JSON or not.

Validating JSON in javascript.

Javascript provides two methods to work with JSON.

JSON.strinfify which converts a JSON data to a string and JSON.parse which converts string back to the JSON.

We can use the JSON.parse method by wrapping it inside a try catch block to check if the string is properly parsed or not. If it throws error while parsing that means it is not a valid JSON.

const isJson = (str) => {
   try{
      JSON.parse(str);
   }catch (e){
      //Error
      //JSON is not okay
      return false;
   }
 
  return true;
}