-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e9579fd
commit 238acfb
Showing
3 changed files
with
32 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
--- | ||
title: Check if a JavaScript string is a valid JSON | ||
shortTitle: Check if string is valid JSON | ||
type: tip | ||
language: javascript | ||
tags: [type] | ||
cover: italian-horizon | ||
excerpt: Use a simple JavaScript trick to validate a serialized JSON object. | ||
dateModified: 2024-03-17 | ||
--- | ||
|
||
When working with serialized data, you might come across some malformed or invalid JSON strings from time to time. While JavaScript doesn't have a built-in validation method for JSON, it has a handy `JSON.parse()` method that can be used to check if a string is a valid JSON. | ||
|
||
Reading through the documentation, you'll find that `JSON.parse()` **throws** a `SyntaxError` if the string is **not a valid JSON**. We can use this to our advantage by wrapping the `JSON.parse()` method in a `try...catch` block to check if the string is valid. | ||
|
||
```js | ||
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 | ||
``` |