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

fetch解析JSON后属性取值始终返回undefined问题排查

问题成因
  • 接口返回内容不符合标准JSON语法规范:标准JSON要求所有对象键必须使用双引号包裹,你当前接口返回的是无引号键名的JS对象字面量格式,JSON.parse(data)执行时会直接抛出语法错误,进入catch分支。
  • catch分支逻辑存在缺陷:异常触发时你直接将原始响应文本(字符串类型)赋值给json变量,此时json不是解析后的JS对象。控制台能打印出完整内容是因为字符串本身可被正常输出,但字符串不存在title/icon/desc/type自定义属性,读取这些属性时全部返回undefined,因此空值合并运算符??始终返回预设的默认值。
修复方案
  1. 修正接口返回的JSON格式,为所有对象键添加双引号,符合JSON标准规范,修正后的返回内容如下:
{
    "title": "Store Name",
    "icon": "/storeicon.png",
    "desc": "Eventual Description",
    "type": "1"
}
  1. 优化前端请求解析逻辑,去掉手动转文本再parse的冗余写法,直接使用fetch内置的response.json()方法解析响应,同时增加请求、解析失败的兜底判断,修复后代码如下:
fetch(link)
  .then(response => {
    if (!response.ok) throw new Error(`请求异常,状态码:${response.status}`);
    return response.json();
  })
  .then(json => {
    console.log(json);
    const title = json.title ?? "Store";
    const icon = json.icon ?? `${location.href.replaceAll(location.pathname, '')}/assets/media/apps/store.png`;
    const desc = json.desc ?? `${title} is a Reccomended Store.`;
    const type = json.type ?? "2";

    const targetDom = document.getElementById(`store-reccomended-${i}`);
    targetDom.setAttribute('storetitle', title);
    targetDom.setAttribute('alt', title);
    targetDom.setAttribute('storedesc', desc);
    targetDom.setAttribute('storetype', type);
    targetDom.setAttribute('src', icon);
  })
  .catch(err => {
    console.error('商店配置加载失败,将使用默认配置', err);
  });

排查技巧:后续遇到同类属性读取异常问题,可在打印变量后追加console.log(typeof json),若输出为string说明未成功解析为对象,若输出为object才是可正常读取属性的JS对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 20:24:29