How do you extract JSON data and apply it to an overlay as text?

Hi,
I’m almost done with this practice project that I’ve been working on. The last thing that I need to do is append 3 lines of text. The first line is the name of the artist, the second line is the name of the album, and the third is a link taking you directly to the spotify website specifically for the album which you’ve already clicked on.

Here’s an example of JSON data that I’m using: https://api.spotify.com/v1/search?q=muse&type=album

Here’s all my HTML, CSS, and JavaScript code: https://jsfiddle.net/kautif/z8zkrwks/4/

If you look up an album and click on a thumbnail, it will show the respective image, but will say undefined for every caption. I believe this is related to lines 20 and 46 of my JavaScript.

If you could please help me with the first line of text, then I’ll see if I can do the second and third lines on my own. Thank you.

Hi again,

So the short answer is that album.artists is an array (just like album.images), so you’d have to reference the first item of said array to get the values you need. In other words, change this:

albumHTML += '<img src="' + album.images[0].url + '" alt="' + album.artists.name + '">';

to this:

albumHTML += '<img src="' + album.images[0].url + '" alt="' + album.artists[0].name + '">';

and you will get the name. The rest should be easy after that :slight_smile:


The longer answer is that your code is a bit of a mess and could be tightened up in a number of places. Would you like some help in sorting it out?

Here’s a fiddle demonstrating the first steps (this is basically what I did to work out what was happening where).

Demo

2 Likes

Hey Pullo,
Yea, I’m still learning… I’d appreciate your help in showing me what neater code should look like.

Awesome. Coulpe of quick questions up front:

  • Any reason you’re using such an old version of jQuery?
  • Do you mind using ES6? This means worse compatibility for older browsers, but is not an issue if you are targeting modern browsers. In other words, IE8/9 won’t run ES6 very well, but latest Chrome, FF, IE, Edge, Opera, Safari all will.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.