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

madeinqc
1201 silver badge7 bronze badges
asked Jun 26, 2011 at 19:32
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.

answered Jun 26, 2011 at 19:44
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.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.