jQuery解析多维数组

时间:2012-06-29 07:06:35

标签: jquery ajax json

我正在向外部php文件发出ajax请求,然后返回一些json。大多数json是直截了当的,但我似乎无法弄清楚如何解析多维部分。


JSON:

{
    "success":"TRUE",
    "action":"JSON",
    "date":"06/29/12",
    "results":"true",
    "numResults":2,
    "0":[
        "id":1234,
        "name":"John Appleseed",
        "gender":"male",
        "average":2.5
    ],
    "1":[
        "id":5678,
        "name":"Jessica Smith",
        "gender":"female",
        "average":1.4
    ]
}

jQuery:

$.ajax({
url: "searchController.php",
data: searchData,
type: "GET",
success:function(q) {
    if (q) { // Results
        $('#search .container .body .ajax .returnedHTML .loadingScreen').hide();                                
        var json = $.parseJSON(q);
        console.log(json);
        if (json.success == "true") {
            var numResults = json.numResults;
            if (numResults == 1) {
            $('#search .container .body .ajax .returnedHTML .content').contents().remove();
            var htmlString = '<div class="searchContent"><ul><li class="returnedResults '+json.type+'"><a href="/#!/'+json.type+'/'+json.id+'/"><div class="title">'+json.name+'</div><div class="body"><div class="quickview"><ul><li><div class="average">'+json.average+'</div><br><span>Average</span></li><li><div class="rates">'+json.numrates+'</div><br><span>Rates</span></li><li><div class="followers">'+json.followers+'</div><br><span>Followers</span></li></ul></div></div></a></li></ul></div>';
            $('#search .container .body .ajax .returnedHTML .content').append(htmlString);
            console.log(htmlString);                                          
        }
    }
});

如何解析JSON以便我可以访问所有数据而不仅仅是第一维中的数据?我在这个网站上环顾四周,找不到任何有用和/或有帮助的东西。非常感谢你!

3 个答案:

答案 0 :(得分:2)

您的数组位于json[0]json[1]

 ...
for(var i in json) {
  if(!isNaN(i)) {
    ...
    refer to you variables as json[i].name, json[i].average, etc.
    ...
  }
}                                  

答案 1 :(得分:1)

$.ajax({
url: "searchController.php",
data: searchData,
type: "GET",
success:function(q) {
    if (q) { // Results
        $('#search .container .body .ajax .returnedHTML .loadingScreen').hide();                                
        var json = $.parseJSON(q);
        console.log(json);
        if (json.success.toLowerCase() == "true") {
            ...                                  
        }
    }
});


for(var key in json){
    if(json.hasOwnProperty(key){
       console.log(key);
       console.log(json[key]);
    }    
}

答案 2 :(得分:0)

关于你的JSON,你必须再次进行相同的解析,

var jsonArr1 = $.parseJSON(json.0);
var jsonArr2 = $.parseJSON(json.1);