Something like:
var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString(\"foo\");
Oh you can definitely use try catch to check whether its or not a valid JSON
Tested on Firfox Quantom 60.0.1
use function inside a function to get the JSON tested and use that output to validate the string. hears an example.
function myfunction(text){
//function for validating json string
function testJSON(text){
try{
if (typeof text!=="string"){
return false;
}else{
JSON.parse(text);
return true;
}
}
catch (error){
return false;
}
}
//content of your real function
if(testJSON(text)){
console.log("json");
}else{
console.log("not json");
}
}
//use it as a normal function
myfunction('{"name":"kasun","age":10}')