最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to access json data in javascript? - Stack Overflow

programmeradmin8浏览0评论

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

json looks like this

    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.

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

json looks like this

    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.
Share Improve this question edited May 18, 2020 at 10:53 Jamshaid Alam asked May 18, 2020 at 10:31 Jamshaid AlamJamshaid Alam 5271 gold badge11 silver badges27 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

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 ments!

This is demo json

{
    "name": "mkyong",
    "age": 30,
    "address": {
        "streetAddress": "88 8nd Street",
        "city": "New York"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "111 111-1111"
        },
        {
            "type": "fax",
            "number": "222 222-2222"
        }
    ]
}

follow this code :

<script>
       var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';

    var json = JSON.parse(data);

    alert(json["name"]); //mkyong
    alert(json.name); //mkyong

    alert(json.address.streetAddress); //88 8nd Street
    alert(json["address"].city); //New York

    alert(json.phoneNumber[0].number); //111 111-1111
    alert(json.phoneNumber[1].type); //fax

    alert(json.phoneNumber.number); //undefined
</script>
发布评论

评论列表(0)

  1. 暂无评论