0
votes

I'm trying to get the first top-track preview url from an artist but everytime I do the search it returns a broken json. I can parse it as a string to get what I need but a json would be a lot easier. Here is my code:

const https = require('https');
var open = require('open')

function songError(){
    console.log('There was some kind of error fetching your artist ;(');
}

function getTopSong(p_id){
    https.get('https://api.spotify.com/v1/artists/'+p_id+'/top-tracks?country=BR', function(res){
        res.on("data", function(chunk){
            var json = JSON.parse(chunk.toString('utf8'));
            console.log(json);
        });
    });
}

function getArtistID(p_name) {
    https.get('https://api.spotify.com/v1/search?q='+encodeURI(p_name)+'&type=artist', function(res){
        res.on("data", function(chunk) {
            var json = JSON.parse(chunk.toString('utf8'));
            if(json['artists']['items'][0]['id'] != undefined || json['artists']['items'][0]['id'] != null){
                console.log('id: ',json['artists']['items'][0]['id']);
                getTopSong(json['artists']['items'][0]['id']);
            }else
            {
                songError();
            }
        });
    });
}

getArtistID("rage against the machine");

There seems to be an error in line 329:

undefined:329
  "available_markets" : [ "AR", "AU", "AT", "BE", "BO", "BR", "BG", "CA", "CL", "CO", "CR", "CY", "CZ", "DK", "DO", "DE", "EC", "EE", "SV", "FI", "FR", "GR", "

My question is, am I doing something wrong or is it really broken? Thanks!

1

1 Answers

0
votes

I could curl it without any problems at least:

$ curl -s 'https://api.spotify.com/v1/artists/2d0hyoQ5ynDBnkvAbJKORj/top-tracks?country=BR' | python -mjson.tool | tail
            "id": "25CbtOzU8Pn17SAaXFjIR3",
            "name": "Take The Power Back - Remastered",
            "popularity": 58,
            "preview_url": "https://p.scdn.co/mp3-preview/b44e8f96a219871587d0559970ca5dce71c891f2",
            "track_number": 3,
            "type": "track",
            "uri": "spotify:track:25CbtOzU8Pn17SAaXFjIR3"
        }
    ]
}

I don't know much about nodejs, but don't you need to concatenate all callbacks to res.on("data"?

https://nodejs.org/api/http.html#http_http_request_options_callback

https.get('https://api.spotify.com/v1/artists/' + p_id + '/top-tracks?country=BR', function(res) {
  var body = [];
  res.on("data", function(chunk) {
    body.push(chunk);
  });
  res.on("end", function() {
    var json = JSON.parse(Buffer.concat(body).toString("utf8"));
    console.log(json);
  });
});

If the response is long and Spotify's servers decides to send the response back chunked transfer encoding, then the nodejs http module probably splits the response up as well.