You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Nutritionix API后,如何解析Fetch返回的JSON并获取foods值?

问题分析与解决

问题根源

  • JSON解析逻辑错误:你用response.text()获取接口返回的字符串后,执行JSON.parse(JSON.stringify(result))属于无效操作——这会把原字符串转成带引号的JSON格式字符串,再解析回原字符串,最终result是字符串类型而非JS对象,自然无法通过.foods访问属性。
  • 重复await误用:第一个await result已经将Promise解析为最终值,第二个await result.foods完全多余,且此时result是字符串,不存在foods属性,所以返回undefined。

修正后的代码

直接使用response.json()自动解析JSON为JS对象,简化异步流程:

async function fetchNutritionData() {
  try {
    const response = await fetch("https://trackapi.nutritionix.com/v2/natural/nutrients", requestOptions);
    const result = await response.json(); // 直接解析为JS对象
    
    console.log(result); // 输出完整的对象结构
    console.log('foods: ', result.foods); // 正常访问foods数组
    
    // 遍历foods获取每个食物的卡路里值
    result.foods.forEach(food => {
      console.log(`${food.food_name} 的卡路里:${food.nf_calories}`);
    });
  } catch (error) {
    console.log('error: ', error);
  }
}

如果偏好.then()链式写法,修正解析步骤即可:

let resultPromise = fetch("https://trackapi.nutritionix.com/v2/natural/nutrients", requestOptions)
  .then(response => response.text())
  .then(textResult => JSON.parse(textResult)) // 直接将字符串解析为JS对象
  .catch(error => console.log('error: ', error));

async function processResult() {
  const result = await resultPromise;
  console.log(result);
  console.log('foods: ', result.foods);
  
  // 遍历输出卡路里
  result.foods.forEach(food => {
    console.log(`${food.food_name}: ${food.nf_calories} kcal`);
  });
}

processResult();

内容的提问来源于stack exchange,提问作者Alex West

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 05:15:40