如何在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
相关产品推荐
相关产品推荐

