Something like:
var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString(\"foo\");
I know i'm 3 years late to this question, but I felt like chiming in.
While Gumbo's solution works great, it doesn't handle a few cases where no exception is raised for JSON.parse({something that isn't JSON})
I also prefer to return the parsed JSON at the same time, so the calling code doesn't have to call JSON.parse(jsonString) a second time.
This seems to work well for my needs:
function tryParseJSON (jsonString){
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
};