Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access json data in javascript?

I want to get name value. How do I access it?

json looks like this

enter image description here

    var result = null;
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === this.DONE) {

        result = JSON.parse(this.responseText);

           for(var i = 0; i <= result.total_count; i++)
           {
               console.log(result.data[i].name);
           }
      }
    });

This is giving me result as I want but with an error

Cannot read property 'name' of undefined in log.
like image 295
Jamshaid Alam Avatar asked Aug 15 '26 23:08

Jamshaid Alam


1 Answers

You need to parse your JSON first:

const result = JSON.parse(this.responseText);
console.log(result.data[0].name);

The responseText property you use returns the response as purely text. In this case you are trying to read the data property of a String object. Since this doesn't exist it will be undefined. Next you are trying to access the 0 property of an undefined value which will result in the error you encounter.

Using the JSON.parse method will convert the string to a Javascript object which does have a data property.

Thanks @3limin4t0r for further clarifying in the comments!

like image 149
Mathyn Avatar answered Aug 19 '26 04:08

Mathyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!