Accessing JSON data

2020-02-07 05:57发布

If I am given the following data by a web-service:

{
    "d": [
        {
            "col1": "col 1 data 1",
            "col2": "col 2 data 1"
        },
        {
            "col1": "col 1 data 2",
            "col2": "col 1 data 2"
        }
    ]
}

how do I access the second col1?

As the following:

success: function( data ) {
         alert( data.d ) ;
},

gives me:

[object Object],[object Object]

标签: json jquery
4条回答
孤傲高冷的网名
2楼-- · 2020-02-07 06:11
success:function(data){
data = JSON.parse(data); // you will have to parse the data first
alert(data.d[0].col1);
查看更多
我命由我不由天
3楼-- · 2020-02-07 06:19

Its an array with 2 elements containing col1 and col2, so something like:

alert(data.d[1].col1);

(0 is the first element, and then you choose "col1")

查看更多
女痞
4楼-- · 2020-02-07 06:25

Try this:

var json = {
    "d": [
        {
            "col1": "col 1 data 1",
            "col2": "col 2 data 1"
        },
        {
            "col1": "col 1 data 2",
            "col2": "col 1 data 2"
        }
    ]
};

alert(json.d[1].col1);

Specify the array index of d (starts with 0, so this would be 1) and then you can access child items. Here's a working example on jsFiddle.

查看更多
叼着烟拽天下
5楼-- · 2020-02-07 06:27
alert( data.d[1].col1 ) ;

In human:

  1. start at data variable
  2. go to d property.
  3. d is an array, so look up the value at index 1 (second value)
  4. look up the col1 property of that value.

May I suggest console.log? In Chrome and with Firefox/Firebug it will give you a nice log message which tells you more about your data.

查看更多
登录 后发表回答