AJAX: Check if a string is JSON?
If you include the JSON parser from json.org, you can use its parse() function and just wrap it in a try/catch, like so:
try{ var json = JSON.parse(this.responseText);}catch(e){ alert('invalid json');}
Something like that would probably do what you want.
Hers's the jQuery alternative...
try{ var jsonObject = jQuery.parseJSON(yourJsonString);}catch(e){ // handle error }
I highly recommend you use a javascript JSON library for serializing to and from JSON. eval()
is a security risk which should never be used unless you are absolutely certain that its input is sanitized and safe.
With a JSON library in place, just wrap the call to its parse()
equivalent in a try/catch-block to handle non-JSON input:
try{ var jsonObject = JSON.parse(yourJsonString);}catch(e){ // handle error }