Converting a Response Buffer to JSON

2019-08-29 06:06发布

问题:

In AWS, I am issuing a get request through Lambda with the https module. I am able to return the data, but it is in the buffer format when I call callback(null, obj)

https.get(options, (res) => {
    res.on('data', (d) => {
        var foo = (JSON.stringify(d));
        var foo1 = d.toString('utf8');

        var obj = {
            bar: foo,
            bar1: foo2
        };

        callback(null, obj);
    });
  }).on('error', (e) => {
    console.error(e);
});

Returns this:

Response:
{
   "bar": "{\"type\":\"Buffer\",\"data\":[31,153,38,35,...]}",
   "bar1": "[{\"app_id\":1111111,\"user_id\":111111,....\"}]"
}

How do I convert this to JSON?

回答1:

I figured it out. With tomfa's code found here: BinArraytoJson I simply did:

var binArrayToJson = function(binArray) {
    var str = "";
    for (var i = 0; i < binArray.length; i++) {
        str += String.fromCharCode(parseInt(binArray[i]));
    } 
    return JSON.parse(str)
}

Then: JSON.parse(binArrayToJson(yourBinArray));