Extract arrays and objects from JSON returned with jQuery

Asked

Viewed 743 times

3

I’m making a request on a web service using jQuery this way:

var dados = jQuery( this ).serialize();

jQuery.ajax({
     type: "POST",
     url: "http://meusite.com/test",
     data: dados,
     success: function( data )
     {
         // quero exibir os dados que estão dentro de data
      }
});

The return JSON is exactly when the login user is WRONG.

{
    "error": true,
    "message": "Login failed. Incorrect credentials"
}

If authentication is CORRECT, the result is this:

{
    "error": false,
    "user": [
        {
            "id": 2,
            "fullname": "Romero Brito",
            "email": "[email protected]",
            "created_at": "2017-01-20 01:03:48"
        }
    ]
}

How do I extract arrays and JSON objects returned with jQuery? How do I display the message inside message and through the data?

EDIT

At first the data can be listed simply in a alert() or even only on console.log().

  • Where do you want to show this data? in a table? in an Alert?

  • You want to get the property user?

  • @Sergio at first would not have a specific location, only in log or even in a alert().

  • @Marconi wants to get the elements returned from JSON from within the data. Not only the user, but other objects.

  • @Acklay Would go through the properties without knowing what is coming? More or less that? http://answall.com/questions/127924/percorrer-um-array-sem-saber-seus-indices/127926#127926

2 answers

1


Good night,

if you specify in the options object sent to the method .ajax the key dataType, you tell what kind of data you are expecting from the server. In your case, it would be something like this:

jQuery.ajax({
     /* ... */
     dataType: 'json',
     /*... */
})

However, as a standard (default), jQuery tries to guess - Intelligent Guess -, the received data format (xml, script, json...) from the server response. So this above parameter would only need to be informed if jQuery could not understand that the answer is a JSON (usually due to a badly formatted message by the server), or you want to make sure that the result will always be this (in this case, if jQuery cannot parse, it will invoke callback error).

That said, then, its function-callback success will be invoked with the first parameter containing the formatted data (Parsed) (in your case, a Javascript object). And you can manipulate it as if you were manipulating a javascript object normally. Something like this:

jQuery.ajax({
    /* ... */ 
    success: function(data, textStatus, jqXHR )
     {
         /* seu dado já deve estar no parâmetro data */
         console.log("Login com sucesso? ", !data.error);
         if (!data.error) {
            var user = data.user[0]; //seu user é um array, então pego o primeiro elemento dessa array, por exemplo
            console.log("Nome completo do usuário: ", user.fullname);
         }
     }
});

The above code is for the purpose of debug, as you will write to your browser console.

I do not know if this was your doubt (on how to manipulate the received data).

If you want to display a simple message, you can call the method alert. This will show a dialog box with the message (very simple).

Or, if you want to insert this message into the body of the page in some way, or make interactions of elements, this involves manipulations in the DOM, and can be done easily by jQuery. A very simple example:

jQuery.ajax({
    /* ... */ 
    success: function(data, textStatus, jqXHR )
    {
        var textMessage;
        if (data.error) {
            textMessage = "Ocorreu um erro ao relizar o login: " + data.message;
        } else {
            textMessage = "Login realizado com sucesso! Bem vindo, " + data.user[0].fullname + "!";
        }
        $("body").append( $("<p></p>", { text: textMessage }) );
    }
});

The above example just adds to the <body> one <p> (paragraph) with a message.

  • Cool your explanation, but it didn’t hurt dude. I tried to show the part of the message, but it appears that data.message is undefined

  • @Acklay corrected the last example. I had the logic reversed.

  • @Was Acklay there giving the error? The first example worked as you expected?

  • The data.message worked well, but the data.user[0]. fullname does not work.

  • You can make a console.log(data); and inspect your object. Can post here the result? you posted up there that key user receives an array. So that would be the way to access that object. data.user[0] gets the first array item data.user

  • You were right, man, I was wrong about something else here. Hugs. Vlw.

  • You’re welcome. Good luck on the project. Hugs

Show 2 more comments

1

Using dataType as json you can get the return in this format to iterate the keys or values.

jQuery.ajax({
  type: "GET",
  url: "https://raw.githubusercontent.com/luccascosta/library/master/js/ret.json",
  dataType: "json",
  success: function(data) {
    console.log(data);
    console.log(data['message']);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

For the return of user

jQuery.ajax({
  type: "GET",
  url: "https://raw.githubusercontent.com/luccascosta/library/master/js/user.json",
  dataType: "json",
  success: function(data) {
    console.log(data);
    console.log(data.user[0].fullname); // user[0] é para acessar o index zero do array de user. Dessa forma é possível acessar qualquer propriedade do objeto dentro desse array
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

PS: In the example is method get only to illustrate the return.

  • This works for the message. And in case of user, how does it have to be done? Sorry ignorance.

  • No ignorance. I edited the answer @Acklay.

Browser other questions tagged

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