How to check if Ajax's return is JSON or String?

3

My code looks like this:

sendAjax(new FormData(this), function(retorno) {
    if(retorno.isArray)
    {
        $(".erro-login strong").text("ID: " + retorno.id + " usuário: " + retorno.usuario);
        $(".erro-login").show("slow");
        navigator.notification.beep(1);
    }
    else
    {
        $("input[name = usuario]").val(retorno);
        $(".erro-login strong").text(retorno);
        $(".erro-login").show("slow");
        navigator.vibrate(1);
    }
});

The variable retorno can be of type String or a Array JSON , I want to know how do I differentiate this in Jquey ? I tried to use isArray but it did not work, it keeps entering else with the return value for example:

{
"tipo":1,
"usuario":"Guilherme",
"key":"66bd30f0cf4309c4ad7308fff5efffe8"
}

In short, how to differentiate a variable when it is JSON or String?

    
asked by anonymous 17.05.2016 / 20:44

3 answers

3

Try using the following function:

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }

    return true;
}

// exemplo de uso
var str = '{'
  + '"tipo":1,'
  + '"usuario":"Guilherme",'
  + '"key":"66bd30f0cf4309c4ad7308fff5efffe8"'
  +'}';

alert(isJson(str));
    
17.05.2016 / 21:23
6

A JSON passed from the server to the client is a String , a JSON after parse in JavaScript, is an Object . So if you need to know if it's string or not just know typeof json == 'string' . To be sure you can do this:

sendAjax(new FormData(this), function(retorno) {
    if (typeof retorno != 'string') {
        // é Objeto JSON
        // etc...
    } else {
        // é um string, precisa de JSON.parse(json) para ser usado como Objeto
        // etc...
    }
});

jQuery allows you to pass a parameter on the Ajax configuration object to decide what kind of data to receive. If you pass dataType: 'json' then you can be sure that you receive an Object.

$.ajax(url, {
  dataType: 'json',
  success: function(data) {
    // etc...
    
17.05.2016 / 21:10
0

Object.is is not yet supported by all browsers, but you can do a Polyfill for browsers that do not support ES6, natively it compares two objects to see if they are the same, but you can add or overwrite them :

var foo = {
  "foo": "foo"
};

Object.is = function(obj) {
  var r = (typeof obj) == 'object' ? true : false;
  return r;
};


console.log(Object.is(foo));
    
17.05.2016 / 21:52