nodejs解析json响应中的对象

时间:2020-09-20 09:37:34

标签: javascript node.js json

我决定在这个周末尝试一些新的东西,并启动了一个NodeJS项目,这应该给我随机发行一首新的Spotify歌曲。因此,我正在使用node-spotify-api npm模块。看来我设法对Spotify API进行了身份验证,但我不知道如何正确访问响应。到目前为止,这是我的代码:

// Get random Song
app.get('/getrandomsong', async (req, res) => {
    console.log('Starting to search for a random song');
    // Authenticate to spotify api
    const spotify = new Spotify({
        id: process.env.SPOTIFY_ID,
        secret: process.env.SPOTIFY_SECRET
    });

    // Make the actual request 
    spotify
        .request('https://api.spotify.com/v1/browse/new-releases?limit=1')
        .then(function(data) {
        console.log(data);
    }) .catch(function(err) {
        console.log('Error occured: ' + err);
    });
});

控制台日志向我显示以下响应。如何访问和使用[Object]中的信息?

Starting to search for a random song
{
  albums: {
    href: 'https://api.spotify.com/v1/browse/new-releases?offset=0&limit=1',
    items: [ [Object] ],
    limit: 1,
    next: 'https://api.spotify.com/v1/browse/new-releases?offset=1&limit=1',
    offset: 0,
    previous: null,
    total: 100
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用data.albums.items

进行访问

通过执行以下操作,您还可以检查items数组的内容以查看对象是什么

data.albums.items.forEach(arr => {
  console.log(arr)
})
相关问题