24

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":"[email protected]"}}]

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

Thanks

0

1 Answer 1

52

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.

Sign up to request clarification or add additional context in comments.

10 Comments

The final call should be res.on('end', function(err) { ... }); nodejs.org/docs/v0.4.8/api/http.html#event_end_
This seems like a lot of work to get json from a server. Is there anything in node now to shorten this... I think jQuery spoiled me $.get('url', function(d) { console.log(d); });
Is it better to use data = [] then data.push(chunk) then JSON.parse(data.join('')) ? since strings are immutable?
Not really, well not in V8 atleast. stackoverflow.com/questions/7299010/…
How can I fetch req.param after parsing? Req is not an input.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.