2012-11-27 50 views
2

後不確定這裏的JSON字符串的示例:入門JSON解析的jQuery

{ 
     "table": { 
     "tfoot": "Footer", 
     "tr0": [ 
        { 
        "form": "formData", 
        "td": "Content" 
        } 
       ] 
     } 
    } 

而jQuery代碼我使用解析它:

$.ajax({ 
    type: 'GET', 
    url: source, 
    dataType: 'json', 
    success: function (data) { 

      $.each(data, function() { 
       $.each(this, function(key, value) { 
       switch (key) { 
        case "tfoot": 
         alert(value) // access to this node works fine      
        break; 

        default: 
         alert(value.td) // this is undefined 
        break; 
       }  
       }); 
      }); 
     } 
    }); 

我嘗試了用CONSOLE.LOG鉻和我可以看到每個節點和數據是好的。任何人都有線索如何訪問「表單」或「TD」節點?

+1

[]表示它的一個數組變量。所以你應該有另一個循環tr0或只使用tr0 [0]。 – arunes

+0

http://stackoverflow.com/a/5514133/1288 http://stackoverflow.com/a/13586208/1288 –

回答

0

value.table.tr0 [0] .td

是你在找什麼。

0

在json {}中定義了一個json對象,[]定義了一個json數組。

因此,自"tr0"出現[](數組)後,您需要使用索引訪問它。 value.table.tr0[0].td應該工作

1

對象值是一個數組,因此您不能訪問它的td屬性。如果你想獲得到陣列中的第一項TD屬性,你需要做的:

value[0].td 

全碼:

$.each(t, function() { 
    $.each(this, function(key, value) { 
    switch (key) { 
     case "tfoot": 
     console.log(value) // access to this node works fine      
     break; 

     default: 
     console.log(value[0].td) // this now prints "Content" 
     break; 
    }  
    }); 
});