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

如何从fetch POST请求的响应中提取指定的嵌套属性值?

问题原因

你当前获取到的result是JSON格式的纯字符串,不是可以直接读取属性的JavaScript对象,这是因为你调用了response.text()将响应体解析为了纯文本格式,所以直接使用点语法或者方括号读取属性自然会返回undefined。
另外你之前尝试的result.totalResponse.address.number路径也有错误:返回结构中address和totalResponse是同级的顶层属性,不需要经过totalResponse即可访问。

解决方法

方法1:直接使用fetch自带的JSON解析(推荐)

将response.text()替换为response.json(),fetch会自动把响应的JSON内容转为JS对象,可直接读取属性:

var myHeaders = new fetch.Headers();
raw = "srvrwd-ui=useMe"

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://www.example.net", requestOptions)
.then(response => response.json()) // 替换此处的text为json
.then(result => console.log(result.address.number)) // 按正确层级读取属性
.catch(error => console.log('error', error));

方法2:手动解析JSON字符串

如果你需要保留response.text()的用法,可以手动调用JSON.parse()将字符串转为JS对象后再读取:

fetch("https://www.example.net", requestOptions)
.then(response => response.text())
.then(result => {
  const resObj = JSON.parse(result)
  console.log(resObj.address.number)
})
.catch(error => console.log('error', error));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:15:03