How to check if return from Ajax is JSON or String?

Asked

Viewed 4,243 times

4

My code is 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 may be of the String or a Array JSON, I want to know how I differentiate that in Jquey? I tried to use the isArray but it didn’t work, it keeps going into the else with the return valid for example:

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

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

  • What ajax are you wearing? jQuery?

  • 1

    The backend return that is always text(string) would have to do a retorno = JSON.parse(retorno); to turn it into json 'for real'.

  • Yes, the ajax is from Jquery, I’ll try it here the way @rray quoted it.

  • 1

    @lvcs the accepted answer is a good tool but for another type of problem. In your case you use jQuery with dataType: 'json' as you said, then you always receive an Object and the code of the accepted answer always gives the same result(!)... that’s what you want?

  • I tested all answers with and without dataType that in my case was indifferent since I could add or remove it without harming the rest of the code, and the only answer that managed to be functional was the one I marked, the others did not work with dataType or without it.

  • And you tested if that method works true and false? or always gives the same answer?

Show 1 more comment

3 answers

6

A JSON passed from server to client is a String, a JSON after done parse, in Javascript, is a Object. So if you need to know if it’s string or not just know typeof json == 'string'. To be sure you can do it like 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 in the Ajax configuration object to decide the type 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...
  • I did so, but anyway he enters the if(typeof retorno != 'string'), even though the return is a string, although dataTYpe is json

  • 1

    @lvcs if the dataType is JSON then is an object, not a string. If you are using jQuery Ajax with dataType: 'json' you will always receive an object.

  • 1

    I didn’t know that detail dataType +1

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

0

Object.is is not yet supported by all browsers, but you can do a Polyfill for browsers that do not support ES6, it natively compares two objects to see if they are equal, 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));

  • 2

    I think this answer (and the answer accepted) answers something else than the question problem. AP says "ajax is from Jquery" and that the dataType is json. That’s why he always gets an object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.