2012-09-16 40 views
0

JSON對象我有一個JSON對象構造如下:瀏覽使用jQuery

<? 
$t['w'][$id]['marchin']=$machin; 
$t['w'][$id]['c'][$id_com]['machin']=$machin;  
echo json_encode($t); 
?> 

我瀏覽對象這樣

// here i access to all the $t['w'][$id] 

$.each(data.w, function(k,v){ 

       var that=this; 
       doSomething(); 

       // now i want to access to all the $t['w'][$id]['c'] 
       $.each(that.c, function(k1,v1){ 
        doSomething();  
       }); 

}); 

但在此間舉行的第二jQuery的每個犯錯誤.. 如何訪問所有$ t ['w'] [$ id] ['c'] ?!

謝謝


好吧,我嘗試:

   $.each(data.w, function(k,v){ 
        var that = $.parseJSON(this); 
         doSomething(); 

        $.each(that[k]['c'], function(k1,v1){ 
         doSomething(); 

       }); 

     }); 

,但它不會再次工作,

這裏是我的JSON的例子,

{"w": 
    {"3": 
     {"test":"test","c": 
     {"15": 
      {"test2":"test2"} 
     } 
     } 
    } 
} 
+0

你不介意發佈JSON嗎? – Stphane

+0

你有沒有開始通過解析json字符串回到一個對象與'var myObj = $ .parseJSON(data);' – adeneo

回答

1

數據...

var data = {"w": 
    {"3": { 
     "test":"test", 
     "c": { 
      "15": {"test2":"test2"} 
     } 
     } 
    } 
}; 

環......

$.each(data.w, function(key, value){ 
    // you are now lopping over 2nd dimension 
    // On each loop, 'key' will be equal to another [$id] value 
    // since you know you'd like to crawl 'c' sub entry, you can reference it 
    // and loop over it 
    $('body').append('<h3>'+key+'</h3>'); 
    if(this['c']) 
    $.each(this['c'], function(k,v){ 
     // Here you have access to ['c'][...] 
     $('body').append('<span>'+k+'</span>'); 
    }); 
}); 
+0

這沒有工作我貼了代碼,你能幫忙嗎? – user1475195

+0

當然,讓我們把這個... jsfiddle.net/ZDb6j/ ...現在作品...要編輯我的文章 – Stphane

0

你可以做到這一點沒有。每次都:

var hsh = $.parseJSON(data.w); 

for (var i in hsh) { 
    var that = hsh[i]; 
    doSomething(); 

    for (var j in hsh[i].c) { 
    doSomething(); 
    } 
}