Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Parse JSON object

Tags:

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

like image 207
donald Avatar asked Jun 26 '11 19:06

donald


People also ask

How do I parse a JSON object in node JS?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How do you parse an array of JSON objects in Node JS?

nodejs-parse-json-file.js json', // callback function that is called when reading file is done function(err, data) { // json data var jsonData = data; // parse json var jsonParsed = JSON. parse(jsonData); // access elements console. log(jsonParsed.

How do I convert a JSON object to a string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

How do I access a JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.


1 Answers

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.

like image 125
RobertPitt Avatar answered Nov 04 '22 11:11

RobertPitt