json获得位置0的属性

时间:2013-05-06 04:34:04

标签: javascript jquery json

所以,如果我有以下json

{
"data": {
    "sectionList": {
        "section124": [{
                "a": "test",
                "b": "test",
                "c": "test",
                "d": "test",
                "e": "test2013-04-14"
            }, {
                "a": "test",
                "b": "test",
                "c": "test",
                "d": "test",
                "e": "test2013-04-14"
            }
        ]
    },
    "section00824": [
        [{
                "a": "test",
                "b": "test",
                "c": "test",
                "d": "test",
                "e": "test2013-04-14"
            }, {
                "a": "test",
                "b": "test",
                "c": "test",
                "d": "test",
                "e": "test2013-04-14"
            }
        ]
    ]
}

}

我在我的代码中做了一个ajax get on并且有一个返回结果的回调我需要知道第一部分是什么叫

我知道我可以这样做:

return result.data.sectionList.section124;

但问题是我不知道这个名字是什么,因为它每次都可以改变

我试过

return result.data.sectionList.*;
return result.data.sectionList[0];

但不允许使用

任何想法?

感谢

3 个答案:

答案 0 :(得分:3)

如果您只有一个部分,那么您可以通过执行Object.keys(result.data.sectionList)[0]之类的操作来获取其名称。但是,如果您有多个部分并且想要第一个部分,则不能从result对象执行此操作,因为JavaScript中的对象不保留密钥顺序。

答案 1 :(得分:1)

您可以使用for each循环在sectionList中迭代,如下所示:

for each (var item in result.data.sectionList) {
  //ur stuff here
}

你也可以像这样使用普通for循环:

for(var item in result.data.sectionList){
  var itemValue= result.data.sectionList[item ];
  //ur stuff here
}

答案 2 :(得分:0)

它是key value对。订购无法保证。

您可以for(key in result.data.sectionList){}获取密钥并返回您想要的内容。