Files
30-seconds-of-code/snippets/isValidJSON.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

537 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
isValidJSON type,intermediate 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