
Use JavaScript to determine whether a string is a valid JSON string
Validate JSON strings in JavaScript using JSON.parse() in a try...catch block with additional protection.
To determine whether a string is a valid JSON string in JavaScript, you can use the JSON.parse()
method within a try...catch
block. This approach leverages the fact that JSON.parse()
throws a SyntaxError
exception if the input string is not valid JSON. By catching this exception, you can accurately determine if the string represents valid JSON.
In simpler terms, “determining if the provided text is a valid JSON string” means checking if a piece of text (or string) follows the rules of the JSON (JavaScript Object Notation) format. JSON is a way to store and exchange data between a server and a web application. It uses a specific structure where data is organized in key-value pairs, similar to how you might organize items in a dictionary. The validation process ensures that the text looks like something that could be turned into a JSON object, meaning it’s well-formed according to the rules of JSON.
Check if provided string is a valid JSON string code
The below isValidJSON
function is designed to determine whether a given input string represents valid JSON.
We’ll enhance our code a bit by determining the value type and length of the text.
const isValidJSON = (text) => {
let isValid = false;
if (typeof text !== 'string' || (typeof text === 'string' && text.length === 0)) {
return isValid;
}
try {
JSON.parse(text);
isValid = true;
} catch (e) {
console.error('[isValidJSON], invalid JSON text', text);
}
return isValid;
}
Code explanation
Here’s a breakdown of how it works:
- Function definition: The function takes one parameter,
text
, which is expected to be a string representing JSON content. - Initial check: It starts by setting a variable
isValid
to the defaultfalse
result. This variable will be used to track whether the input string is considered valid JSON. Input validation:
- First, it checks if the input
text
is not a string or if it is an empty string (""
). - If either condition is true, it immediately returns the current value of
isValid
, which remainsfalse
because the input does not meet the basic criteria for being valid JSON.
- First, it checks if the input
Parsing attempt:
- If the input passes the initial validation, the function attempts to parse the string using
JSON.parse()
. JSON.parse()
tries to convert the string into a JavaScript object. If the string is valid JSON, this operation succeeds, and the function setsisValid
totrue
.
- If the input passes the initial validation, the function attempts to parse the string using
Error handling:
- If
JSON.parse()
throws an error (which happens when the string is not valid JSON), the function catches this error and logs it to the console with a message indicating that the input was invalid JSON. - Despite the error, the function still returns the current value of
isValid
, which would now befalse
due to the parsing failure.
- If
- Return value: Finally, the method returns the result of
isValid
, which shows if the input text included valid JSON. A return result oftrue
indicates that the string was properly parsed into a JavaScript object, implying that it was valid JSON. Afalse
return result indicates that the string was invalid JSON, either because it was not a string, was empty, or had syntax issues that prevented effective processing.
Comments