Files
30-seconds-of-code/snippets/js/s/is-valid-json.md
2023-05-07 16:07:29 +03:00

556 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
String is valid JSON snippet javascript
type
italian-horizon 2020-10-18T13:49:49+03:00

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