My JavaScript sometimes crashes on this line:
var json = eval('(' + this.responseText + ')');
Crashes are caused when the argument of eval()
is not JSON. Is there any way to check if the string is JSON before making this call?
I don't want to use a framework - is there any way to make this work using just eval()
? (There's a good reason, I promise.)
All json strings start with '{' or '[' and end with the corresponding '}' or ']', so just check for that.
If the response is JSON, a properly behaving application would set the Content-Type to application/json. So all you have to do, if the server is well-behaving, is to test if the Content-Type header in the response starts with application/json. By chance, jQuery already does this by itself: $.
In order to check the validity of a string whether it is a JSON string or not, We're using the JSON. parse()method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.
Validating with JSONObject String json = "Invalid_Json"; assertFalse(validator. isValid(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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With