Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API:
fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population')
.then(function (response) {
return response.json();
})
.then(function(data) {
appendData(data);
})
.catch(function(err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
var div = document.createElement("div");
div.innerHTML = 'Name: ' + data[0].Population;
mainContainer.appendChild(div);
// }
}
<html lang="en">
<head>
<meta charset="UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON Test</title>
</head>
<body>
<div id="myData"></div>
</body>
</html>
The goal is to retrieve the "Population" data for 2019 and showcase it. While dealing with simple APIs that do not involve arrays or complex structures, it's relatively straightforward. However, in this case, I seem to be struggling with differentiating between arrays and objects while coding it - any tips or suggestions on how to tackle this?