我最近一直在浏览器中使用ajax来使用spotify api,到目前为止我还没有遇到任何问题。但是现在我尝试将它与node.js一起使用,我只是做一个简单的get并尝试将字符串解析为JSON对象,但是我得到了一个语法错误。这是代码:
var https = require('https')
var dir = "https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist"
https.get(dir, function (response){
response.setEncoding('utf8');
response.on('data', function (data){
var str = data;
var jObj = JSON.parse(str);
console.log(jObj);
})
})
这是我收到的响应,并希望将其解析为Json对象:
{
"artists": {
"href": "https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist",
"items": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/08td7MxkoHQkXnWAYD8d6Q"
},
"followers": {
"href": null,
"total": 21
},
"genres": [],
"href": "https://api.spotify.com/v1/artists/08td7MxkoHQkXnWAYD8d6Q",
"id": "08td7MxkoHQkXnWAYD8d6Q",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/f2798ddab0c7b76dc2d270b65c4f67ddef7f6718",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/b414091165ea0f4172089c2fc67bb35aa37cfc55",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/8522fc78be4bf4e83fea8e67bb742e7d3dfe21b4",
"width": 64
}
],
"name": "Tania Bowra",
"popularity": 4,
"type": "artist",
"uri": "spotify:artist:08td7MxkoHQkXnWAYD8d6Q"
}
],
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total": 1
}
}
这是我得到的错误:
undefined:16
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (C:\path:12:19)
at IncomingMessage.emit (events.js:107:17)
at IncomingMessage.Readable.read (_stream_readable.js:373:10)
at flow (_stream_readable.js:750:26)
at resume_ (_stream_readable.js:730:3)
at _stream_readable.js:717:7
at process._tickCallback (node.js:355:11)
浏览器中的相同请求完美无缺,并且在http://jsonlint.com/
中签入时,Json格式中没有出现任何错误答案 0 :(得分:1)
将收到每个数据块调用'data'回调函数,因此您必须收集所有数据然后解析它:
https.get(dir, function (response){
var str = '';
response.setEncoding('utf8');
response.on('data', function (data){
str += data;
});
response.on('end', function (){
var jObj = JSON.parse(str);
console.log(jObj);
});
})