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":"chris@example.com"}}]

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

Thanks

madeinqc
  • 120
  • 1
  • 7
donald
  • 23,587
  • 42
  • 142
  • 223

1 Answers1

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.

RobertPitt
  • 56,863
  • 21
  • 114
  • 161
  • 7
    The final call should be res.on('end', function(err) { ... }); http://nodejs.org/docs/v0.4.8/api/http.html#event_end_ – Kevin Decker Jun 26 '11 at 19:52
  • 1
    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); }); – Langdon Apr 01 '12 at 14:20
  • 2
    Is it better to use data = [] then data.push(chunk) then JSON.parse(data.join('')) ? since strings are immutable? – King Friday Dec 29 '12 at 19:49
  • 1
    Not really, well not in V8 atleast. http://stackoverflow.com/questions/7299010/why-is-string-concatenation-faster-than-array-join – RobertPitt Jan 24 '13 at 10:51
  • How can I fetch req.param after parsing? Req is not an input. – János Apr 16 '14 at 11:16
  • @Langdon It's totally generic - write this function once; you can use for every response, regardless of where/what it is, or what you do with it. – OJFord Aug 05 '15 at 14:29
  • @János Well, you have the `req`, you made it! You also have `res.req`. (and `res.req.res.req`, and ...) – OJFord Aug 05 '15 at 14:30
  • @OllieFord This is from 3+ years ago, and ExpressJS already solved the problem. – Langdon Aug 05 '15 at 16:14
  • @Langdon Then if there's now a better way, consider providing the answer for the thousands of people viewing the question, and seeing only this one. – OJFord Aug 05 '15 at 16:17
  • @Langdon An answer that says "use express" would not be answering the original question proposed here. The accepted answer here is the correct way to do it if you're writing vanilla node. But you shouldn't be writing vanilla node anymore, as there are a ton of frameworks that greatly ease development. – Langdon Aug 05 '15 at 16:29