如何在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("未获取到商家数据"); } });
关键说明
- 直接使用
response:res.json()已经完成了解析,不需要额外的序列化和反序列化。 - 通过数组索引访问元素:用
response[0]获取数组中的第一个对象,再访问其merchant_name属性。 - 增加空值判断:防止数组为空时出现报错,提升代码健壮性。
内容的提问来源于stack exchange,提问作者Nosi Ishmael
相关产品推荐
相关产品推荐

