Skip to content

Commit c0c1c12

Browse files
authored
Add Function to check if string is valid JSON (#1168)
* Create readme.md * Create checkStringisValidJson.js * Added isValidJSON function to verify if the string is valid JSON and log the result * Create README file with title, description, usage, and examples for isValidJSON function.
1 parent b5c7278 commit c0c1c12

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Function to check if a string is a valid JSON
2+
function isValidJSON(str) {
3+
try {
4+
// Try to parse the string as JSON
5+
JSON.parse(str);
6+
} catch (e) {
7+
// If an error occurs, the string is not valid JSON
8+
return false;
9+
}
10+
// If no error occurs, the string is valid JSON
11+
return true;
12+
}
13+
14+
// Example JSON string
15+
const str = '{ "firstName":"John" , "lastName": "Doe"}';
16+
17+
// Check if the string is valid JSON and log the result
18+
if (isValidJSON(str)) {
19+
console.log('String is valid JSON');
20+
} else {
21+
console.log('String is not valid JSON');
22+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Function to check if string is a valid JSON
2+
3+
## Problem statement
4+
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 format.
5+
6+
## Description
7+
The `isValidJSON` function checks if a given string is a valid JSON format. It tries to parse the string and returns `true` if the parsing is successful and `false` if an error occurs during the parsing process.
8+
9+
## Usage
10+
This function is useful for validating JSON strings before attempting to use them in your application.
11+
12+
## Examples
13+
14+
### Example 1
15+
```javascript
16+
const str = '{ "firstName": "John", "lastName": "Doe" }';
17+
```
18+
This will output: `String is valid JSON`
19+
20+
### Example 2
21+
```javascript
22+
const invalidStr = '{ firstName: John, lastName: Doe }';
23+
```
24+
This will output: `String is not valid JSON`

0 commit comments

Comments
 (0)