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

