List JSON data with Javascript

Asked

Viewed 965 times

6

I’m trying to list the data of a JSON through Javascript, but it only presents in the list a position 0.

Below follows the JSON:

[
   {
      "id":"23"
   },
   {
      "id":"24"
  }
]

I have the following code below which is a return of an AJAX request:

success: function(getApi) {


  for (var i = 0; i < getApi.length; i++) {
    var id = getApi[i].id;


    var dados = '<li class="list-group-item">' +
      '<a href="#" class="media shadow-15">' +
      '<div class="w-auto h-100">' +
      '<figure class="avatar avatar-40"><img src="img/espaco.jpg" alt=""> </figure>' +
      '</div>' +
      '<div class="media-body">' +
      '<h5 class=" mb-0">' + id + '</h5>' +
      '<p><span class="badge mb-1">Teste</span></p>' +
      '</div>' +
      '</a>' +
      '</li> ';

    $(".resultApi").html(dados);
  }
}

How do I show them all IDs of my JSON?

  • 1

    At the beginning of your function put a console.log(getApi); and put the result of this in your question

3 answers

5

It’s because you’re wearing .html() when you should use .append(). The .html() will replace the HTML of the target element with each iteration in for, resulting only the code of the last for. Should be:

$(".resultApi").append(dados);

Also check that dados is a parsed JSON (probably is). If you don’t need to include the option in your Ajax:

dataType: "json",
  • 1

    I believe the fact of dados being a JSON is already implicit in the question, since if it was a string JSON, the getApi[i].id would be producing an error, which was not mentioned in the question.

  • 3

    True Felipe... only put even with an add-on in the answer... In fact it would not even give error, would "Undefined" :D

  • 3

    "Better to have and not need than to need and not have" xD

  • 1

    Yeah, that’s right. :)

  • 1

    @Sam another one of the series: "happened to me". Worse than me I did a p#†@trampo and the guy got accepted answer with 3 lines of reply. And the focus of my answer was just what he had "copied and changed the words".

  • @Sam, thank you very much! solved my problem friend.

  • @Sam, actually, I started writing the answer before you sent yours. Your answer may have even been posted earlier, but I assure you I did not copy it. :/

  • @Luizfelipe Tranquil. This has happened mt. I think the two answers add.

Show 3 more comments

5

Your problem is that you are redefining the HTML of the item after each iteration (loop). This will only make the last ID of the array be shown, since all previous ones have been reset by the following iteration.

So instead of redefine the content, you should simply add the data generated in each iteration to the previously created data.


See your problem in a slightly simpler example:

const $list = $('#my-list')
const ids = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]

for (let i = 0; i < ids.length; i++) {
  const id = ids[i].id
  const html = `<li>${id}</li>`
  
  console.log('ID atual:', id, ' | HTML atual:', html)
  
  // Note que, ao invés de você acrescentar o HTML gerado ao final da lista,
  // você simplesmente está redefinindo todo o HTML definido anteriormente,
  // ao usar o método .html().
  $list.html(html)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="my-list"></ul>

To resolve this, as mentioned earlier, you need to add the HTML generated to final of the list. For this, we will use the method append jQuery. So:

const $list = $('#my-list')
const ids = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]

for (let i = 0; i < ids.length; i++) {
  const id = ids[i].id
  const html = `<li>${id}</li>`
  
  console.log('ID atual:', id, ' | HTML atual:', html)
  
  // Agora, ao invés de redefinir o HTML após cada iteração, estamos simplesmente
  // acrescentando o HTML gerado ao conteúdo, já existente, da lista:
  $list.append(html)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="my-list"></ul>


So, in your code, you must change the html (replacing existing HTML with a new HTML) by append (adding a new HTML to an existing HTML). From:

$(".resultApi").html(dados);

To:

$(".resultApi").append(dados);
  • 1

    Luiz Felipe, thank you so much for the solution. Solved my problem and took out a great doubt I had from the append. Thank you so much!

1


You can use jQuery to call your json file to display its full list.

$(document).ready(function() {

function dadosJson() {
    $.getJSON('dados.json', function(json) {
        $.each(json, function() {
            let info = '<p>' + this['id'] + '</p>';
            $('#boxTeste').append(info);
        });
    });/*GetJson end*/ 
}/*function end*/ 

    dadosJson();

});

$.getJSON will fetch your file with the json, the function .each will scroll through your json file searching for the 'id' parameters and displaying them when creating them through Function .append(info) within the da div specifies

Browser other questions tagged

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