Skip to content

Commit

Permalink
Tipify is-valid-json
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed Mar 17, 2024
1 parent e9579fd commit 238acfb
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 27 deletions.
3 changes: 3 additions & 0 deletions content/redirects.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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!
27 changes: 0 additions & 27 deletions content/snippets/js/s/is-valid-json.md

This file was deleted.

29 changes: 29 additions & 0 deletions content/snippets/js/s/string-is-valid-json.md
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
```

0 comments on commit 238acfb

Please sign in to comment.