-1

I try to parse this JSON object, but always got 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);
            });
halfer
  • 19,824
  • 17
  • 99
  • 186
Nurdin
  • 23,382
  • 43
  • 130
  • 308

3 Answers3

4

Documentation here about the fetch api and 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);
        });

If you did just want to get the text and then parse it, do it like you did but then do const dataObj = JSON.parse(data); console.log(dataObj.success.name);

TKoL
  • 13,158
  • 3
  • 39
  • 73
0

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

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);
    });

Reference: https://www.w3schools.com/js/js_json_parse.asp

Googlian
  • 6,077
  • 3
  • 38
  • 44
0

You have to parse JSON to object first.

let parsedData = JSON.parse(data);
console.log(parsedData);

JSON.parse()

Jax-p
  • 7,225
  • 4
  • 28
  • 58