-1

I am attempting to access the content of a JSON object returned from an API call in order to set variables.

var request = require('request');
var apiOptions = { server : "http://localhost:3000" };


var renderAdminLanding = function(req, res, body){
  var str = JSON.stringify(body.content, null, 2);
  res.render('admin_landing', {
    title: str});
}
module.exports.landing = function(req, res){
  var reqOptions, path;
  path = '/api/student';
  reqOptions = {
    url : apiOptions.server + path,
    method : "GET",
    json : true
  }
  request(reqOptions, function(err, response, body){
    renderAdminLanding(req, res, body);
  });
};

In this case body.content returns:

[ { "_id": "58ca92faa0c1e14922000008", 
    "name": "Smarty", 
    "password": "McSmartface", 
    "__v": 0, 
    "Courses": [] } ]

So body.content.name, for example returns nothing.

Tyler B. Joudrey
  • 421
  • 1
  • 8
  • 22
  • 1
    [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Mar 18 '17 at 14:42
  • 1
    `body.content` is an array. To access the first element in that array, you have to write `body.content[0]`, and to get the name of the first element `body.content[0].name` – t.niese Mar 18 '17 at 14:42
  • Possible duplicate of [JavaScript Object property always returns undefined](http://stackoverflow.com/questions/20716618/javascript-object-property-always-returns-undefined) – t.niese Mar 18 '17 at 14:55

1 Answers1

3

As @t.niese said, body.content is an array. You can say that it's an array because your object is encased in square brackets: [{"myObject": 3}].

Since body.content is an array, you have to get the position that your object is on the array. While body.content.name does not exist and will return undefined or throw an error, body.content[0].name will return Smarty, which is what you expected.

guilherme.oc97
  • 431
  • 1
  • 3
  • 13