尝试将 Spotify 响应字符串解析为 node.js 中的 json 对象

Trying to parse spotify response string into json object in node.js

我最近一直在使用 spotify api,在浏览器中使用 ajax,到目前为止我没有遇到任何问题。但现在我试图将它与 node.js 一起使用,我只是在做一个简单的获取并尝试将字符串解析为 JSON 对象,但我在 return 中遇到语法错误。这是代码:

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)

相同的请愿书在浏览器中运行完美,并且在 Json 格式中没有错误,因为我在 http://jsonlint.com/

中检查过

收到的每个数据块都会调用'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);
  });
})