Files
30-seconds-of-code/snippets/isValidJSON.md
2018-12-04 12:43:44 +08:00

23 lines
424 B
Markdown

### isValidJSON
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
```