Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs read JSON data from a http request chunk

Tags:

json

rest

node.js

I am using Jira API's to get data on single tickets. I have successfully setup a http GET request to the server and can display the data to the console however I ideally need to get certain properties from the data which is in JSON format.

When I try to read the properties I just get undefined.

var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);         // This displays the JSON
    console.log('endSTATUS: ' + chunk.id); // This shows up undefined
});    

The data is in this format from jira API for reference. The first console log in the res successfully displays all the data from the chunk. The second one is:

endSTATUS: undefined
like image 912
Dom Avatar asked Dec 18 '22 12:12

Dom


2 Answers

Try to get the body after the data stream finish. Like this:

        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {

            // Data reception is done, do whatever with it!
            var parsed = JSON.parse(body);
            console.log('endSTATUS: ' + parsed.id);
        });
like image 200
lucas.coelho Avatar answered Jan 08 '23 20:01

lucas.coelho


Make sure you are parsing the response data as JSON. I think you may want something like var data = JSON.parse(chunk);, and reference the chunk data as data.value.

res.on('data', function (chunk) {
var data = JSON.parse(chunk);
console.log('BODY: ' + data);         
console.log('endSTATUS: ' + data.id); 
});
like image 25
arbybruce Avatar answered Jan 08 '23 21:01

arbybruce