Something like:
var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString(\"foo\");
I used a really simple method to check a string how it's a valid JSON or not.
function testJSON(text){
if (typeof text!=="string"){
return false;
}
try{
JSON.parse(text);
return true;
}
catch (error){
return false;
}
}
Result with a valid JSON string:
var input='["foo","bar",{"foo":"bar"}]';
testJSON(input); // returns true;
Result with a simple string;
var input='This is not a JSON string.';
testJSON(input); // returns false;
Result with an object:
var input={};
testJSON(input); // returns false;
Result with null input:
var input=null;
testJSON(input); // returns false;
The last one returns false because the type of null variables is object.
This works everytime. :)