Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Function to check if a string is a valid JSON
function isValidJSON(str) {
try {
// Try to parse the string as JSON
JSON.parse(str);
} catch (e) {
// If an error occurs, the string is not valid JSON
return false;
}
// If no error occurs, the string is valid JSON
return true;
}

// Example JSON string
const str = '{ "firstName":"John" , "lastName": "Doe"}';

// Check if the string is valid JSON and log the result
if (isValidJSON(str)) {
console.log('String is valid JSON');
} else {
console.log('String is not valid JSON');
}
24 changes: 24 additions & 0 deletions Background Scripts/Check String is Valid JSON/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Function to check if string is a valid JSON

## Problem statement
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.

## Description
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.

## Usage
This function is useful for validating JSON strings before attempting to use them in your application.

## Examples

### Example 1
```javascript
const str = '{ "firstName": "John", "lastName": "Doe" }';
```
This will output: `String is valid JSON`

### Example 2
```javascript
const invalidStr = '{ firstName: John, lastName: Doe }';
```
This will output: `String is not valid JSON`