Jackanapes Jackanapes - 6 months ago 13
Javascript Question

Accesing data in JS after API request?

Trying to use the google fonts API to learn interacting with APIs etc. Whenever I try to access the data after parsing using dot notation it doesn't work, for example trying:

console.log(fonts);


or

console.log(fonts.family);


or

console.log(font.items[1].family);


Doesn't work, with all of these resulting in an array for either fonts or items not being declared. However, the .length of .items is output just fine, so I'm wondering if I have a fundamental misunderstanding with how to access this information?

Code:

var fontRequest = new XMLHttpRequest();
fontRequest.onreadystatechange = function() {
if (fontRequest.readyState === 4 && fontRequest.status === 200) {
var fonts = JSON.parse(fontRequest.responseText);
var family = fonts.items.family;
var statusHTML = '<ul class="fonts">';
for (var i = 0; i < fonts.items.length; i += 1) {
statusHTML += '<li>' + i + ' ' + family + '</li>';
document.getElementById('googleFonts').innerHTML = statusHTML;
}
}

};
fontRequest.open('GET', 'https://www.googleapis.com/webfonts/v1/webfonts?key=?????');
fontRequest.send();


(Key has been hidden)

Example of JSON recieved from request.

Example of JSON recieved from request.

Could anyone tell me how, for example, to print out items.family inside of the loop?

plnkr here:
https://plnkr.co/edit/mabE27maz64bQwM6G1JD?p=preview

Answer

As per your result displayed in image, you should call

var family = items[0].family;

output will be ABeeZee

Edit

Update your javascript function with following

var fontRequest = new XMLHttpRequest();
fontRequest.onreadystatechange = function() {
    if (fontRequest.readyState === 4 && fontRequest.status === 200) {
        var fonts = JSON.parse(fontRequest.responseText);
        //var family = fonts.items[0].family;
        var statusHTML = '<ul class="fonts">';
        for (var i = 0; i < fonts.items.length; i += 1) {
            statusHTML += '<li>' + i + ' ' + fonts.items[i].family + '</li>';
            document.getElementById('googleFonts').innerHTML = statusHTML;
        }
    }
};
fontRequest.open('GET', 'https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyAyORnIjrvRi3StxS2gVuvIUBYPY7MZXiE');
fontRequest.send();
Comments