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

如何在JavaScript中访问API返回的数组形式JSON对象

访问API返回数组中元素的正确方法

你的问题出在API返回的是数组而非单个对象,直接用info.merchant_name自然拿不到值,另外代码里还有冗余的JSON转换步骤。

问题分析

  • API返回的JSON格式是:

    [{"merchant_id":"90151","merchant_name":"Wimpy"}]
    外层是数组,里面包含一个商家对象。

  • 你用res.json()已经把响应解析成了JavaScript数组,后续的JSON.stringify再JSON.parse完全是多余操作,不会改变数据结构。
  • 直接访问info.merchant_name相当于给数组对象找merchant_name属性,数组本身没有这个属性,所以返回undefined。

修正后的代码

fetch("http://127.0.0.1:8000/vcl/retrieve/"+url, {
  method: "GET",
  headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.then((response) => {
  console.log(response);
  // 先从数组中取出第一个商家对象
  const merchant = response[0];
  if (merchant) {
    const merchant_name = merchant.merchant_name;
    console.log(merchant_name); // 输出 "Wimpy"
  } else {
    console.log("未获取到商家数据");
  }
});

关键说明

  1. 直接使用response:res.json()已经完成了解析,不需要额外的序列化和反序列化。
  2. 通过数组索引访问元素:用response[0]获取数组中的第一个对象,再访问其merchant_name属性。
  3. 增加空值判断:防止数组为空时出现报错,提升代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:33:10