Reputation: 109
I am trying to fetch data from this url - https://dog.ceo/api/breeds/list/all which has some empty values. Basically I am trying to build a table with the list of dog breeds.
$.getJSON("https://dog.ceo/api/breeds/list/all", function(data) {
$.each(data, function(index, d) {
$('#api-details tbody').append("<tr>" +
"<td>" + d + "</td>" +
"</tr>")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="api-details" class="table">
<thead class="thead-light">
<th>List of Breeds</th>
</thead>
<tbody>
</tbody>
</table>
This is not returning the list of breeds but just sends an object to the HTML.
Upvotes: 1
Views: 87
Reputation: 337580
Each breed is held within the keys of the message
object in the response. As such you need to loop over those instead of the data
object as a whole.
Also note that within each family of dog breed is the individual breed names, so you will need a second loop to output those as well. Try this:
$.getJSON("https://dog.ceo/api/breeds/list/all", function(data) {
var rows = '';
Object.keys(data.message).forEach(function(family) {
rows += '<tr><td>' + family + '</td></tr>';
data.message[family].forEach(function(breed) {
rows += '<tr><td> - ' + breed + '</td></tr>';
})
});
$('#api-details tbody').append(rows);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="api-details" class="table">
<thead class="thead-light">
<th>List of Breeds</th>
</thead>
<tbody>
</tbody>
</table>
Upvotes: 1
Reputation: 2065
That json
data has two objects status and message, your data is stored in message
So you need to apply each
for data.message
Please check below code :
$.getJSON("https://dog.ceo/api/breeds/list/all", function (data) {
$.each(data.message, function (index, d) {
if (d != "") {
$('#api-details tbody').append("<tr>" +
"<td>" + d + "</td>" +
"</tr>")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="api-details" class="table">
<thead class="thead-light">
<tr><th>List of Breeds</th></tr>
</thead>
<tbody></tbody>
</table>
Upvotes: 0