diff --git a/content/redirects.yaml b/content/redirects.yaml index 22073841f6b..e8859894119 100644 --- a/content/redirects.yaml +++ b/content/redirects.yaml @@ -2743,3 +2743,6 @@ - from: /js/s/random-number-in-range to: /js/s/random-number-or-integer-in-range status: 301! +- from: /js/s/is-valid-json + to: /js/s/string-is-valid-json + status: 301! diff --git a/content/snippets/js/s/is-valid-json.md b/content/snippets/js/s/is-valid-json.md deleted file mode 100644 index 5906d387e1d..00000000000 --- a/content/snippets/js/s/is-valid-json.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: String is valid JSON -type: snippet -language: javascript -tags: [type] -cover: italian-horizon -dateModified: 2020-10-18 ---- - -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; - } -}; - -isValidJSON('{"name":"Adam","age":20}'); // true -isValidJSON('{"name":"Adam",age:"20"}'); // false -isValidJSON(null); // true -``` diff --git a/content/snippets/js/s/string-is-valid-json.md b/content/snippets/js/s/string-is-valid-json.md new file mode 100644 index 00000000000..8f4335fee79 --- /dev/null +++ b/content/snippets/js/s/string-is-valid-json.md @@ -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 +```