How to check if a response (date) is a json

4

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 {
            }
    
asked by anonymous 10.12.2014 / 18:35

2 answers

9

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
}
    
10.12.2014 / 18:45
2

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;
};

Example:

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);
    
10.12.2014 / 23:43