Files
30-seconds-of-code/snippets/isValidJSON.md
Angelos Chalaris 611729214a Snippet format update
To match the starter (for the migration)
2019-08-13 10:29:12 +03:00

463 B

title, tags
title tags
isValidJSON type,json,intermediate

Checks if the provided string is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided string is a valid JSON.

const isValidJSON = str => {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
};
isValidJSON('{"name":"Adam","age":20}'); // true
isValidJSON('{"name":"Adam",age:"20"}'); // false
isValidJSON(null); // true