getJSON Ajax for JSON with multiple objects

Asked

Viewed 1,101 times

0

To search for data in a JSON simple, like:

{
    "chave1":"valor1",
    "chave2":"valor2"
}

I use something like this:

$.getJSON(dados, function(json) {
    $.each(json, function() {
        $('#r').append("<p>"+this.chave1+"</p>");
    });
})

But the case is now JSON in format:

{"tab":[{
    "urlimg":"1.jpg",
    "nome":"Jhonatan",
    "sobrenome":"Pereira"},
    {"urlimg":"1.jpg",
    "nome":"Jhonatan",
    "sobrenome":"Pereira"}],
"dados":[{
    "algum":"valor",
    "qualquer":"valor2"}],
"outro":[{
    "numero_versao":"1",
    "nome_versao":"v0.1B"}]
}

This is because PHP returns 3 queries, and I need to pass all the results in a single request.

Aids?

  • That’s simple. What part of this JSON you want to use?

  • Take a look here and tell us what part (or how) you need to use in your code: https://jsfiddle.net/qfjtoza7/

  • Speak Sergio, I need to take the "key value" of each session at a time. In this case, you would need to upload "tab", in a second moment of "data", etc. This is for the creation of a dynamic photo album, where in Json the first is the years, the second the months and the third the photos. To facilitate, we can exchange tab, data and other for "year", "month" and "photos"

  • Okay, and have you seen my jsFiddle? Can you see how I’m using JSON there? That’s what you’re looking for?

  • Exactly that :) Just reply to my vote. Thank you!

2 answers

1

You can continue using the same, only with one more iteration on the returned object.

$(document).ready(function () {
   $.getJSON('dados.json', function (dados) {

       var objKeys = Object.keys(dados);

       for (var key in objKeys) {
           imprimirConsulta(objKeys[key], dados);
       }
   });

   function imprimirConsulta(consulta, dados) {
       if (!dados.hasOwnProperty(consulta)) {
           console.error('Dados não possuem consulta', consulta);
           return;
       }

       var $div = $('<div></div>');
       $div.append('<div>' + consulta.toUpperCase() + '</div>');

       var obj = dados[consulta];

       obj.forEach(function (obje) {
           $.each(obje, function (chave, valor) {
               $div.append('<div>Chave: ' + chave + '    Valor: ' + valor + '</div>');
           });

           $div.append('<div style="margin: 5px;"></div>');
       });

       $('.content').append($div);
       $('.content').append('<div style="border-bottom: 1px solid black;"></div>')
   }
});

1


The way you work will not change, what you should pay attention to is the treatment that will be done on each part of the JSON that returns. See:

$.getJSON(dados, function(json) {

  //para cada *value* é necessário indicar o nome da coluna(índice): value.indice
  //pois no json informado, *value* trata-se de um array

  //tratamento da "tab"
  $.each(json.tab, function(key, value) {
     $('#tab').append( "<p> key=" + key + "& value=" + value.urlimg +  "</p>" );
     $('#tab').append( "<p> key=" + key + "& value=" + value.nome +  "</p>" );
     $('#tab').append( "<p> key=" + key + "& value=" + value.sobrenome +  "</p>" );
  });

  //tratamento dos "dados"
  $.each(json.dados, function(key, value) {
     $('#dados').append( "<p> key=" + key + "& value=" + value.algum + "</p>" );
  });

  //tratamento da "outro"
  $.each(json.outro, function(key, value) {
     $('#outro').append( "<p> key=" + key + "& value=" + value.nome_versao + "</p>" );
  });
})

That’s assuming you know which parameters will be returned. If you do not know but want it to return all parameters in certain div’s is also possible so:

$.getJSON(dados, function(json) {
  //para cara parametro execute o $.each
  $.each(json, function(key, value) {
      //defino em qual sub-array do json estará sendo trabalhado
      var param = json[key];
      //usa o nome do 'param' para definir qual div, EX: #tab => "#"+'tab'
      $.each(param,function(key, value){
        $('#' + key).append( "<p> key=" + key + "& value=" + value + "</p>" );
      });
  });
})

Now I see you’re working with jQuery. I advise you to find out more about pure Javascript because it is more "readable" also saves codes in certain cases as in the $.each(). NOTE: That doesn’t mean you can’t mix the two, like this:

//sabendo quais campos serão enviados
$.getJSON(dados, function(json) {
  //tratamento da "tab"
  for(var key in json.tab){
    $('#tab').append( "<p> key=" + key + "& value=" + json.tab + "</p>" );
  };
  //tratamento dos "dados"
  for(var key in json.dados){
    $('#dados').append( "<p> key=" + key + "& value=" + json.dados + "</p>" );       
  };
  //tratamento da "outro"
  for(var key in json.outro){
    $('#outro').append( "<p> key=" + key + "& value=" + json.outro + "</p>" );
  };
})

//sem saber quais campos mas querendo colocar todos (2º exemplo)
$.getJSON(dados, function(json) {
  //para cara sub-objeto, trate seus parâmetros
  for (var p in json)
      //defino em qual sub-array do json estará sendo trabalhado
      var param = json[p];
      //usa o nome do 'param' para definir qual div, EX: #tab => "#"+'tab'
      for(var key in param)
        $('#' + key).append( "<p> key=" + key + "& value=" + param[key] + "</p>" );
      });
  });
})
  • You are returning an object in the "value": tab key=0& value=[Object Object] key=1& value=[Object Object] dice key=0& value=[Object Object] another key=0& value=[Object Object]

  • I did, instead of value, placed value.urlimg, value.name, value.last name, for example.

Browser other questions tagged

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