从我的json响应中访问一组特定的值?

时间:2012-06-07 08:45:18

标签: javascript jquery json

我正在尝试使用for..in循环来访问“事件”中的描述键/值,但目前还不完全确定如何实现这一点。首先,我使用了for..in并将其记录下来,这将返回响应中的所有顶级条目,我现在如何向下钻取并选择Event.description?我首先想到的是数据[prop] .Event.description但事实并非如此。我应该使用正常的for循环,然后使用for..in吗?

这是我目前的代码:

$(document).ready(function() {

    var data = {
        "status": "ok",
        "code": "200",
        "message": "event details",
        "data": [{
            "Event": {
                "id": "1",
                "name": "Sample Event Number 1",
                "description": "Sample Event Number 4 Description ....",
                "event_date": "2012-05-31 00:00:00",
                "Band": [{
                    "id": "1",
                    "name": "Support #1",
                    "BandsEvent": {
                        "id": "7",
                        "band_id": "2",
                        "event_id": "8",
                        "created": "2012-05-23 15:53:56",
                        "modified": "2012-05-23 15:53:56"
                    }},
                {
                    "id": "2",
                    "name": "Support #2",
                    "BandsEvent": {
                        "id": "8",
                        "band_id": "1",
                        "event_id": "8",
                        "created": "2012-05-23 15:53:57",
                        "modified": "2012-05-23 15:53:57"
                    }}]
            }},
        {
            "Event": {
                "id": "2",
                "name": "Sample Event Number 2",
                "description": "Sample Event Number 4 Description ....",
                "event_date": "2012-05-31 00:00:00",
                "Band": [{
                    "id": "2",
                    "name": "Another Crazy Band",
                    "BandsEvent": {
                        "id": "3",
                        "band_id": "2",
                        "event_id": "8",
                        "created": "2012-05-23 15:53:56",
                        "modified": "2012-05-23 15:53:56"
                    }},
                {
                    "id": "4",
                    "name": "The Band",
                    "BandsEvent": {
                        "id": "8",
                        "band_id": "1",
                        "event_id": "8",
                        "created": "2012-05-23 15:53:57",
                        "modified": "2012-05-23 15:53:57"
                    }}]

            }}]
    }


    var prop;

    for (prop in data) {
        console.log( data[prop] );
        // data.Event.description 
    }

});​

1 个答案:

答案 0 :(得分:1)

这应该做你想要的:

for (var i = 0; i < data.data.length; i++) {
    console.log(data.data[i].Event.description);        
}

我应该补充一点,你的代码不起作用的原因是“prop”变量首先是“status”,然后是“code”,然后是“{ {1}}“然后”message“。状态/代码/消息没有“事件”属性,因此如果您尝试访问data,则代码将返回undefined。在这里我们专门挑选它们。由于data.data是一个数组,因此没有理由使用data[prop].Event循环,而只是一个常规for循环。

同样,如果您想要打印出描述和乐队,您可以执行以下操作:

for .. in