I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation.
isJSON = async(str) => {
try {
return (JSON.parse(str) && !!str);
} catch (e) {
return false;
}
}
var testJSON = '{"name": "foo"}'
var number = 22
console.log("result is : ", isJSON(testJSON))
console.log("result is : ", isJSON(number))
The variable str
holds the input value and this function checks if the value is of json
type or not. However, it returns true even for numeric input values like str=22
. My intention is to only check if the input value is in the json
format. Can you help me resolve this issue?