Files
30-seconds-of-code/snippets/isValidJSON.md
Isabelle Viktoria Maciohsek 02faddb6a8 Tags housekeeping
2020-10-18 13:49:49 +03:00

26 lines
461 B
Markdown

---
title: isValidJSON
tags: type,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.
```js
const isValidJSON = str => {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
```
```js
isValidJSON('{"name":"Adam","age":20}'); // true
isValidJSON('{"name":"Adam",age:"20"}'); // false
isValidJSON(null); // true
```