Files
30-seconds-of-code/snippets/is-valid-json.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

555 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
String is valid JSON type italian-horizon 2017-12-31T14:53:01+02:00 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