【问题标题】:Access content of JSON object访问 JSON 对象的内容
【发布时间】:2017-03-18 14:38:44
【问题描述】:

我正在尝试访问从 API 调用返回的 JSON 对象的内容以设置变量。

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);
  });
};

在这种情况下 body.content 返回:

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

所以 body.content.name,例如,什么都不返回。

【问题讨论】:

标签: javascript json node.js express requestjs


【解决方案1】:

正如@t.niese 所说,body.content 是一个数组。您可以说它是一个数组,因为您的对象包含在方括号中:[{"myObject": 3}]

由于body.content 是一个数组,因此您必须获取对象在数组中的位置。虽然body.content.name 不存在并且将返回未定义或抛出错误,但body.content[0].name 将返回Smarty,这正是您所期望的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多