Files
30-seconds-of-code/snippets/isValidJSON.md
Angelos Chalaris 4eb1f086d3 Apply suggestions from code review
Co-authored-by: Isabelle Viktoria Maciohsek <maciv@hotmail.gr>
2022-02-15 09:19:59 +02:00

545 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
String is valid JSON 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