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

API返回JSON响应调用response.message返回undefined 无法获取内部数组问题求解

问题原因

  • 接口返回的response是原始JSON字符串类型,并非已解析完成的JavaScript对象,字符串本身不存在message属性,因此直接读取response.message必然返回undefined。
  • 错误写法JSON.parse(response.message)逻辑顺序完全颠倒:必须先将完整的response字符串解析为JS对象,才能读取下属属性,先读取不存在的属性再做解析自然无法拿到有效值。
  • 额外提示:你提供的简化JSON示例中存在重复的element1键,实际业务中重复键会被后定义的内容覆盖,不属于本次问题的核心诱因,但后续开发需要注意规避。
  • 你使用JSON.stringify处理的操作完全不符合需求:JSON.stringify的作用是把JS对象转为JSON字符串,你拿到的响应本身就是字符串,调用该方法只会多套一层转义引号,进一步增加属性读取的难度。

解决方法

先完成全局JSON解析,再读取目标属性即可,正确代码如下:

globalService.commonService('getData', reqPkg).then((response) => {
  // 第一步:把完整JSON字符串转为JS对象
  const parsedResponse = JSON.parse(response);
  // 第二步:从解析后的对象中读取message数组
  $scope.theReport.data = parsedResponse.message;
});

如果需要增加异常容错逻辑,可以参考下面的写法:

globalService.commonService('getData', reqPkg).then((response) => {
  try {
    const parsedResponse = JSON.parse(response);
    // 可先判断响应状态再处理数据
    if (parsedResponse.status === 'success') {
      $scope.theReport.data = parsedResponse.message;
    } else {
      console.error('接口返回异常', parsedResponse);
    }
  } catch (err) {
    console.error('JSON解析失败', err, '原始响应内容:', response);
  }
});

内容的提问来源于stack exchange,提问作者Peter The Angular Dude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:36:07