【问题标题】:Get Image out of a json response从 json 响应中获取图像
【发布时间】:2021-09-15 16:10:16
【问题描述】:

我正在制作一个与 last.fm API 通信的 discord.js 机器人。我希望我的机器人在嵌入中显示来自请求的图像,但它只会给我不同尺寸的结果。其他一切都很好,我只需要图像方面的帮助。非常感谢你的帮助:)

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)

这是 json 响应

 {
      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'
        }
      ]
    }

【问题讨论】:

  • 使用对象表示法访问链接。 <JSON>.image[x]['#text'], x 是你想要的索引
  • @Elitezen 那么您将如何获得比方说的小图像?我对 json 很陌生,对不起
  • .image 是一个数组,使用数组索引。 .image[0] 返回第一个小元素。查看Arrays - MDN

标签: json discord.js last.fm


【解决方案1】:

在 JSON 响应中,您会注意到为您提供了 Array 的图像。对于 Array 中的每个 JSON 对象,都有一个大小和一个图像 URL。如果你想访问图像的“小”版本,你会要求数组中的第一个元素。计算机从 0 开始而不是 1,因此您可以执行以下操作:

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

如果您想要中等,只需将 0 替换为 1。要了解有关数组的更多信息,请查看 Array article written by Mozilla

感谢@Elitezen,因为他们在 cmets 中指出了这一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2017-08-29
    • 2022-06-28
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多