Trying to practice JSON

Trying to practice JSON
0.0 0

#1

Hello,

I am moving very slowly through JSON trying to understand it. I found a test dataset (https://learnwebcode.github.io/json-example/animals-1.json). For now, all I want to do is pull the dataset from a URL and display it on my web page.

I see that the code is creating the <p> tags I want with the text in it. But can someone explain why the text/data is not showing up on the webpage? (This has less to do with JSON than just javascript).

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>AJAX and JSON</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="AJAX.js"> </script>
  </head>
  <body>
    <p id="p1">replace this text</p>
  </body>
</html>

JS:

$.getJSON("https://learnwebcode.github.io/json-example/animals-1.json", function(data){
  // console.log(data);
  // $("p").innerHTML = data;
for (i=0; i<data.length; i++){
  var para = document.createElement("p");
  var node = document.createTextNode(data[i].name);
  para.appendChild(node);
  console.log(para);
  // document.getElementById("p1").innerHTML = data[i].name;
}
});

Many thanks!


#2

You have not specified exactly how you want to display the data on your page, but I assume you want to replace the existing text of “replace this text” inside the p element with id=“p1” with what you create via your for loop. If that is the case, it seems odd to nest three p elements inside another p element.

I recommend changing your p element with id=“p1” to a div element with id=“div1” and since you want to replace the contents (the “replace this text”) of the element, you will need to clear out the contents first (think innerHTML = “”). The following would be as close to your original solution logic but actually accomplish the task.

$.getJSON("https://learnwebcode.github.io/json-example/animals-1.json", function(data) {
    div1 = document.getElementById("div1");
    div1.innerHTML = "";
    for (var i = 0; i < data.length; i++) {
      var para = document.createElement("p");
      var node = document.createTextNode(data[i].name);
      para.appendChild(node);
      div1.appendChild(para);
    }
  }
);

A more efficient and concise version would be to skip creating and appending each element/textNode and just build the html and only update the DOM one time by replacing the inner html of the div with id=“div1”.

$.getJSON('https://learnwebcode.github.io/json-example/animals-1.json', data => {
  div1.innerHTML = data.reduce((html, animal) => html.concat(`<p>${animal.name}</p>`) ,'');
});