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

使用Fetch获取JSON后无法提取全部host_id的问题求助

解决方法

你的JSON结构是数组包裹着一个对象,这个对象里的键"0"、"1"才对应每个host的数据。原来的循环只遍历了外层数组(长度为1),所以只能拿到第一个host。要获取全部host_id,需要遍历内层对象的所有属性:

修改后的完整代码

// 替换成你的JSON文件实际路径
fetch('hosts.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    appendData(data);
  })
  .catch(function(err) {
    console.log(err);
  });

function appendData(data) {
  // 取出外层数组中唯一的、包含所有host的对象
  const hostObj = data[0];
  // 把对象中的所有host数据转换成数组,方便遍历
  const hosts = Object.values(hostObj);
  
  // 遍历每个host对象
  hosts.forEach(host => {
    console.log(host.host_id); // 打印所有host_id
    
    // 将host_id展示到页面div中(需确保页面存在id为"hostList"的div)
    const itemDiv = document.createElement('div');
    itemDiv.textContent = `Host ID: ${host.host_id}`;
    document.getElementById('hostList').appendChild(itemDiv);
  });
}

关键修改说明

  • 用Object.values(hostObj)将内层对象的所有值(即每个host的详情)转为数组,解决了原结构无法直接按索引遍历的问题
  • 替换原循环为forEach遍历所有host对象,确保能拿到全部host_id
  • 添加了页面展示逻辑,需提前在HTML中添加容器:<div id="hostList"></div>

如果偏好使用for...in循环,也可以这样写:

function appendData(data) {
  const hostObj = data[0];
  for (const key in hostObj) {
    if (hostObj.hasOwnProperty(key)) {
      console.log(hostObj[key].host_id);
      // 同样可添加页面展示逻辑
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:52:52