简体   繁体   中英

Parsing Tinysong return with Nodejs

I am trying to parse the response I get from a query to Tinysong. I am able to make the get and have it console.log but I am not able to do anything with the data after that. I think this is because of how I am capturing it. Full disclosure this is my first time doing a this so I have just mashed together a lot of different examples.

If you navagate to the URL you get something like this:

{"Url":"http:\/\/tinysong.com\/1kxG6","SongID":41760691,"SongName":"Begin Again","ArtistID":9472,"ArtistName":"Knife Party","AlbumID":9855703,"AlbumName":"Abandon Ship"}

This is what I have.

function TinySong (A, S){
    A = A.replace(/ /g,"+");
    S = S.replace(/ /g,"+");
    var url = 'http://tinysong.com/b/' + A + "+" + S + '?format=json&' + TinyKey;
    http.get(url, function(res){
        var bodyChunks = [];
        res.on('data', function(chunk) {
            bodyChunks.push(chunk);
        }).on('end', function() {
            var body = Buffer.concat(bodyChunks);
//             console.log(url)
            console.log('' + body);
        })
    });
}

This console logs something like this:

{"Url":"http:\/\/tinysong.com\/1ksPa","SongID":40778838,"SongName":"Cut Your Teeth (Kygo remix)","ArtistID":2002910,"ArtistName":"Kyla La Grange","AlbumID":9
833902,"AlbumName":"Cut Your Teeth (Kygo remix)"}

But if I don't use console.log('' + body); and i use console.log(body); I get this:

<Buffer 7b 22 55 72 6c 22 3a 22 68 74 74 70 3a 5c 2f 5c 2f 74 69 6e 79 73 6f 6e 67 2e 63 6f 6d 5c 2f 31 6b 73 50 61 22 2c 22 53 6f 6e 67 49 44 22 3a 34 30 37
 37 ...> 

Can anyone help me figure out what I am doing wrong. All help and educated is welcomed.

Thanks FPC

Figured out the answer.

    http.get(url, function(res){
        var data = '';
        res.on('data', function (chunk){
            data += chunk;
        });
        res.on('end', function(){
            var obj = JSON.parse(data);
            console.log(obj)
        });
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM