首页 > 解决方案 > 无法正确解析 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);
            });

标签: javascript

解决方案


此处有关 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);


推荐阅读