Javascript 可以打印出对象,但无法在JS中访问其值

Javascript 可以打印出对象,但无法在JS中访问其值,javascript,json,request-promise,Javascript,Json,Request Promise,我知道这将是一个非常愚蠢的问题,但我一直在竭尽全力想弄明白这一点。我正在使用的API返回以下响应: { "item_id": "51c3d78797c3e6d8d3b546cf", "item_name": "Cola, Cherry", "brand_id": "51db3801176fe9790a89ae0b", "brand_name": "Coke", "item_description": "Cherry", "updated_at": "2013-07-09T

我知道这将是一个非常愚蠢的问题,但我一直在竭尽全力想弄明白这一点。我正在使用的API返回以下响应:

{
  "item_id": "51c3d78797c3e6d8d3b546cf",
  "item_name": "Cola, Cherry",
  "brand_id": "51db3801176fe9790a89ae0b",
  "brand_name": "Coke",
  "item_description": "Cherry",
  "updated_at": "2013-07-09T00:00:46.000Z",
  "nf_ingredient_statement": "Carbonated Water, High Fructose Corn Syrup and/or Sucrose, Caramel Color, Phosphoric Acid, Natural Flavors, Caffeine.",
  "nf_calories": 100,
  "nf_calories_from_fat": 0,
  "nf_total_fat": 0,
  "nf_saturated_fat": null,
  "nf_cholesterol": null,
  "nf_sodium": 25,
  "nf_total_carbohydrate": 28,
  "nf_dietary_fiber": null,
  "nf_sugars": 28,
  "nf_protein": 0,
  "nf_vitamin_a_dv": 0,
  "nf_vitamin_c_dv": 0,
  "nf_calcium_dv": 0,
  "nf_iron_dv": 0,
  "nf_servings_per_container": 6,
  "nf_serving_size_qty": 8,
  "nf_serving_size_unit": "fl oz",
}
这是我试图运行的代码:

var rp = require('request-promise');

module.exports = {
 getIngredients: function(req, callback) {
 rp({
  method: 'GET',
  uri: `https://api.nutritionix.com/v1_1/item?upc=${req.body.upc}&appId=${process.env.NUTRITIONIX_APP_ID}&appKey=${process.env.NUTRITIONIX_APPP_KEY}`
 }).then((data) => {

  console.log(`Talked to NutritionixAPI, result was: ${data}`);
  var ingredients = data.nf_ingredient_statement.split(',');

  console.log(`Ingredients split from the data are: ${ingredients}`);

  return callback(ingredients);

  }).catch((err) => {
   console.log(`Error occured in NutritionixAPI, ${err}`)
   return callback(Object.assign({}, err, { error: true }));
  });
 }
}
我想弄清楚的是,为什么
数据
会正确地打印到控制台,但一旦我试图访问其中的任何值,就会出现
未定义
的错误。我也尝试过JSON中的其他值,因此我非常感谢您的帮助


EDIT:我想澄清问题是关于什么的,不是关于回调和异步调用,因为它们工作得非常好。我的问题是关于
var-components=data.nf_-component_语句.split(',')
其中
nf\u component\u语句
是未定义的,尽管它显然不是。

问题是
数据
是一个JSON字符串,因此在解析它之前不能访问它,这就是为什么
数据。nf\u component\u语句
未定义的

您需要首先解析
数据
,您的代码应该如下所示:

var json = JSON.parse(data);
var ingredients = json.nf_ingredient_statement.split(',');

显然,我得到的是一个JSON字符串。所以我只需要执行
data=JSON.parse(data)
将其解析为实际的JSON。

不要进行
回调<代码>返回
承诺@回调“工作”很好。也许不是首选,但这似乎不是这里的问题。这里的问题可能是
return回调(…)
@Cerbrus中的
return
语句,因为回调中的一切都正常运行。这里的问题是关于
var-components=data.nf_-component_语句.split(',')
where
nf\u-component\u语句
未定义。@清道夫:
data
是JSON字符串吗?(在这种情况下:
data=JSON.parse(data)
)然后将其作为以下内容的副本关闭: