Nico
Nico

Reputation: 323

nodejs parse object in json response

I decided to try something new this weekend and started a NodeJS project, which should give me a random new Spotify song. Therefore I'm using the node-spotify-api npm module. It seems like i managed to authenticate to the Spotify API but I don't know how to access the response correctly. Here is my code so far:

// 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);
    });
});

The console log shows me the following response. How can I access and use the information in [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
  }
}

Upvotes: 0

Views: 56

Answers (1)

EugenSunic
EugenSunic

Reputation: 13723

You can access it by using data.albums.items

You can also check the content of the items array to see what your Object is, by doing the following

data.albums.items.forEach(arr => {
  console.log(arr)
})

Upvotes: 1

Related Questions