There are many sources on how to do so in Javascript, but it seems it's not that simple in Typescript. I want to check if a string is a valid JSON, I have tried the following code:
function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
But no matter what string I try it does not throw an error, even a random string such as "[asc,22"
I have also tried this:
function testJSON(strJson) {
try {
const parsed = JSON.parse(strJson)
if (parsed && typeof parsed === "object") {
return true
}
} catch { return false }
return false
}
But in this case it returns false no matter what string is used, I am not understanding why but the JSON.parse() function always returns a string no matter what I pass it.
I want the function to have results like this:
"123" => false
"abc" => false
"{ "prop_1": "val_1", "prop_2": "val_2" }" => true
"{ prop_1: "val_1", "prop_2": "val_2" }" => false
EDIT: This DOES work in Typescript after verifying on the online platform typescriptlang.org, I am not sure if it might be a problem in ReactJS, the file I am working in is of type .tsx
EDIT 2: The issue turned out not to be related to typescript or react, but the code was misusing elsewhere the "JSON.stringify" method, answer was posted below.