我尝试解析此JSON对象,但总是得到Cannot read property 'name' of undefined
JSON
{
"success": {
"name": "MY NAME"
}
}
JS
fetch("http://MYAPP/api/details")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text();
})
.then(data => {
console.log(data.success.name); // <= ERROR
})
.catch(error => {
console.error(error.message);
});
答案 0 :(得分:4)
Documentation here关于获取api和response.json()
fetch("http://MYAPP/api/details")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json(); // <---- this is what you want
})
.then(data => {
console.log(data.success.name); // <= ERROR
})
.catch(error => {
console.error(error.message);
});
如果您只是想获取文本然后进行解析,请像您一样做,然后再进行const dataObj = JSON.parse(data); console.log(dataObj.success.name);
答案 1 :(得分:0)
使用JavaScript函数JSON.parse()
将文本转换为JavaScript对象:
fetch("http://MYAPP/api/details")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text();
})
.then(data => {
console.log(JSON.parse(data).success.name); // <= ERROR
})
.catch(error => {
console.error(error.message);
});
答案 2 :(得分:0)