Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX: Check if a string is JSON?

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.)

like image 497
Nick Heiner Avatar asked Feb 22 '10 19:02

Nick Heiner


People also ask

How do I check if a string is JSON?

All json strings start with '{' or '[' and end with the corresponding '}' or ']', so just check for that.

How do I know if Ajax response is JSON?

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: $.

How do you check if value is JSON or not?

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.

How do you check if a string is a valid JSON string in Java?

Validating with JSONObject String json = "Invalid_Json"; assertFalse(validator. isValid(json));


2 Answers

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.

like image 159
brettkelly Avatar answered Oct 02 '22 14:10

brettkelly


Hers's the jQuery alternative...

try {   var jsonObject = jQuery.parseJSON(yourJsonString); } catch(e) {   // handle error  } 
like image 35
RayLoveless Avatar answered Oct 02 '22 15:10

RayLoveless