Something like:
var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString(\"foo\");
This answer to reduce the cost of trycatch statement.
I used JQuery to parse JSON strings and I used trycatch statement to handle exceptions, but throwing exceptions for un-parsable strings slowed down my code, so I used simple Regex to check the string if it is a possible JSON string or not without going feather by checking it's syntax, then I used the regular way by parsing the string using JQuery :
if (typeof jsonData == 'string') {
if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
return jsonData;
}
}
try {
jsonData = $.parseJSON(jsonData);
} catch (e) {
}
I wrapped the previous code in a recursive function to parse nested JSON responses.