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

如何在JavaScript中实现Python dict.get()功能解析fetch返回数据

解决方案

你编写的代码存在以下几处问题:

  • detections、source_location 未加引号,会被JS解析为变量而非对象的字符串键
  • 循环逻辑错误,你遍历的是外层data的长度,实际应该遍历detections数组的长度
  • 缺少对应Python dict.get()的容错处理,若detections字段不存在会直接抛出异常
  • 语法错误:console.log 缺少闭合的右括号
  • 无需额外调用JSON.stringify,直接打印字段值即可

最简实现(适配现代JS环境)

等效代码如下:

// 等价于Python的 events_json = events.json()
const eventsJson = await events.json();
// 等价于Python的 events_json.get("detections", []),默认返回空数组避免遍历报错
const detections = eventsJson?.detections ?? [];

// 遍历打印source_location
for (const detect of detections) {
    console.log(detect["source_location"]);
}

兼容旧JS环境的写法

如果你的运行环境不支持可选链和空值合并运算符,可以用如下写法:

const eventsJson = await events.json();
const detections = eventsJson.hasOwnProperty("detections") ? eventsJson.detections : [];

// 也可以用你习惯的普通for循环写法
for (let i = 0; i < detections.length; i++) {
    console.log(detections[i]["source_location"]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:15:02