jsondiscord.jslast.fm

Get Image out of a json response


I'm making a discord.js bot that communicates with the last.fm API. I Want my bot to display the image from the request in an embed but it only gives me the result in different sizes.Everything else works perfectly fine i just need help with the image .Thank you a lot for your help:)

axios
  .get(request_url)
  .then(res => {
    if (res.data.message) {
      message.channel.send('User not found')
      return
    }

    const latest_track = res.data.recenttracks.track[0]

    if (!latest_track) {
      e.message.channel.send('User not found')
      return
    }

    const {
      name,
      artist: { '#text': artist },
      album: {'#text': album},
      image: {'size': large, '#text' : image},
    } = latest_track

   
    
    


    const embed = new MessageEmbed()

      .setColor('#0099ff')
      .setTitle(`🎶now playing- ${fmname}`)
      .setDescription(` **${name} - ${artist}** on ${album}`)
      .setImage(image)

    message.channel.send(embed)

This is the json response

 {
      artist: { mbid: '', '#text': 'Tyler, The Creator' },
      '@attr': { nowplaying: 'true' },
      mbid: '',
      album: { mbid: '', '#text': 'CALL ME IF YOU GET LOST' },
      streamable: '0',
      url: 'https://www.last.fm/music/Tyler,+The+Creator/_/SWEET+%2F+I+THOUGHT+YOU+WANTED+TO+DANCE+(feat.+Brent+Faiyaz+&+Fana+Hues)',
      name: 'SWEET / I THOUGHT YOU WANTED TO DANCE (feat. Brent Faiyaz & Fana Hues)',
      image: [
        {
          size: 'small',
          '#text': 'https://lastfm.freetls.fastly.net/i/u/34s/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
        },
        {
          size: 'medium',
          '#text': 'https://lastfm.freetls.fastly.net/i/u/64s/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
        },
        {
          size: 'large',
          '#text': 'https://lastfm.freetls.fastly.net/i/u/174s/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
        },
        {
          size: 'extralarge',
          '#text': 'https://lastfm.freetls.fastly.net/i/u/300x300/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
        }
      ]
    }

Solution

  • In the JSON response, you'll notice that you're given an Array of images. With each JSON object in the Array, there is a size and an image URL. If you wanted to access the "small" version of the image, you would ask for the first element in the Array. Computers start at 0 as opposed to one so you would do the following:

    // Replace <JSON> with whatever variable represents your JSON
    .setImage(<JSON>.image[0]['#text'])
    

    If you wanted medium, just replace 0 with 1. To learn more about Arrays, check out the Array article written by Mozilla.

    Credit to @Elitezen as they pointed this out in the comments