I am trying to learn more about APIs and calling them correctly. I have been using the fetch method. My code, which includes the API I'm referencing:
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>
I'm trying to call upon "Population" for 2019 and display it. This is easy with a basic API with only one set of curly brackets and no arrays - but for this one I think I'm getting my arrays and objects mixed up and am not coding it in correctly, any suggestions?
CodePudding user response:
This API returns an object with "data"
property so you can use "data"
property to display populations like this.
fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population')
.then(function (response) {
return response.json();
})
.then(function (data) {
const responseData = data.data;
appendData(responseData);
})
.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);
}
CodePudding user response:
Assuming that you want all of the values of the "Population"
key, you'll need to iterate through the data with a loop and/or Array mrthod. The code below targets the "data"
array using data['data']
and on each iteration gets the value of "Population"
using obj['Population']
.
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");
for (let obj of data['data']) {
var div = document.createElement("div");
if (obj['Population']) {
div.innerHTML = 'Population: ' obj['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>