How can I check if a result (date) coming from an ajax request is json or not? I tried this code but I did not succeed
var obj = $.parseJSON(response);
if(obj.avatar) {
} else {
}
How can I check if a result (date) coming from an ajax request is json or not? I tried this code but I did not succeed
var obj = $.parseJSON(response);
if(obj.avatar) {
} else {
}
The method parseJSON
of jQuery throws an exception if JSON is not valid. Therefore:
var obj;
try {
obj = $.parseJSON(response);
// use o JSON aqui
} catch(ex) {
// trate o erro aqui
}
A solution with native JavaScript suggested in SOen would be:
function testarJSON (jsonString){
try {
var o = JSON.parse(jsonString);
if (o && typeof o === "object" && o !== null) return o;
}
catch (e) { }
return false;
};
var jsonValido = '{ "time": "03:53:25 AM", "milliseconds_since_epoch": 1362196405309, "date": "03-02-2013" }';
var jsonInvalido = '"time": "03:53:25 AM", "milliseconds_since_epoch": 1362196405309, "date": "03-02-2013"';
function testarJSON (jsonString){
try {
var o = JSON.parse(jsonString);
if (o && typeof o === "object" && o !== null) return o;
}
catch (e) { }
return false;
};
alert('Nr de JSONs válidos: ' + [jsonValido, jsonInvalido].filter(testarJSON).length);