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
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.
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.
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.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With