javascript - 无法正确解析 JSON 对象
问题描述
我尝试解析这个 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);
});
解决方案
此处有关 fetch 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);
推荐阅读
- sql - 当参数标记是函数参数时无法派生参数信息
- spring - Spring REST控制器文件上传-请求方法'POST'不支持错误
- sql - 在 Postgres 中将 json 字段值更新为小写
- python - Python 3.6 输入崩溃
- apache-spark - 如果 spark.sql.shuffle.partitions 太高,Pyspark 集群在单元测试期间崩溃
- .net-core - Castle Windsor Typed Factory Facility 似乎找不到接口,因为它的命名空间
- sql-server - 使用sql server在单行中显示表的对角行元素
- sql-server - SQL Server 返回一些 unicode 字符的问号
- python - How can I use a dispatcher middleware on flask?
- ruby-on-rails - 根据包含在另一个 json 字段中的字段值选择记录