Fetching json data through http.request, I am able to receive data in chunks, which I push into an array. when the end of the request is signaled, I concatenate the array using buffer.concat, and then json.parse this object, which gives me a string. I then must json.parse this string again to get a json object. Why am I having to json.parse twice? Is there a better way to achieve a valid json object? Here is my code:
// requires Node.js http module
var http = require('http');
var options = {
"method" : "GET",
"hostname" : "localhost",
"port" : 3000,
"path" : `/get`
};
var req = http.request(options, function (res) {
var chunks = [];
console.log(res.statusCode);
res.on("data", function (chunk) {
// add each element to the array 'chunks'
chunks.push(chunk);
});
// adding a useless comment...
res.on("end", function () {
// concatenate the array
// iterating through this object spits out numbers (ascii byte values?)
var jsonObj1 = Buffer.concat(chunks);
console.log(typeof(jsonObj1));
// json.parse # 1
// iterating through this string spits out one character per line
var jsonObj = JSON.parse(jsonObj1);
console.log(typeof(jsonObj));
// json.parse # 2
// finally... an actual json object
var jsonObj2 = JSON.parse(jsonObj);
console.log(typeof(jsonObj2));
for (var key in jsonObj2) {
if (jsonObj2.hasOwnProperty(key)) {
var val = jsonObj2[key];
console.log(val);
}
}
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();