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.
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.