Node.js: Parse JSON object


Question

I am receiving a JSON object as :

http.get(options, function(res) {
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        var obj = JSON.parse(chunk);
        console.log(sys.inspect(obj));
    });
});

And it prints:

BODY: [{"buck":{"email":"chris@example.com"}}]

but now I'm not able to read anything inside it. How do I get the "email" field?

Thanks

1
21
12/8/2016 9:20:23 PM

Accepted Answer

You should be doing something along the lines of:

http.get(options, function(res){
    var data = '';

    res.on('data', function (chunk){
        data += chunk;
    });

    res.on('end',function(){
        var obj = JSON.parse(data);
        console.log( obj.buck.email );
    })

});

If im not mistaken.

49
6/26/2011 9:04:02 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon