Spotify API顶级曲目已损坏

时间:2016-04-22 15:00:00

标签: json node.js spotify

我正在尝试从艺术家那里获得第一个顶级预览网址,但每次我进行搜索时都会返回一个损坏的json。我可以将它解析为字符串以获得我需要的东西,但是json会更容易。这是我的代码:

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");

第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", "

我的问题是,我做错了什么还是真的坏了? 谢谢!

1 个答案:

答案 0 :(得分:0)

我至少可以毫无问题地卷曲它:

$ 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"
        }
    ]
}

我不太了解nodejs,但是你不需要将所有回调连接到res.on("数据"?

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

如果响应很长并且Spotify的服务器决定将响应发送回chunked transfer encoding,那么nodejs http模块可能也会将响应分开。