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
asked Jun 26, 2011 at 19:32
donald
23.8k46 gold badges147 silver badges226 bronze badges
1 Answer 1
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
RobertPitt
57.3k21 gold badges117 silver badges161 bronze badges
Sign up to request clarification or add additional context in comments.
10 Comments
Kevin Decker
The final call should be res.on('end', function(err) { ... }); nodejs.org/docs/v0.4.8/api/http.html#event_end_
Langdon
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); });
King Friday
Is it better to use data = [] then data.push(chunk) then JSON.parse(data.join('')) ? since strings are immutable?
RobertPitt
Not really, well not in V8 atleast. stackoverflow.com/questions/7299010/…
János
How can I fetch req.param after parsing? Req is not an input.
|
lang-js