2013-05-28 81 views
1

我收到了這個JSON文件。路徑數組可以是從1到100,在Json中計數數組insinde數組

{ 
"waypoints": [ 
    { 
     "path0": [ 
      { 
       "color": "#0000FF" 
      }, 
      { 
       "lat": "37.9875000", 
       "lon": "23.7609260" 
      }, 
      { 
       "lat": "37.9873130", 
       "lon": "23.7607460" 
      }, 
      { 
       "lat": "37.9873840", 
       "lon": "23.7604100" 
      } 
     ], 
     "path1": [ 
      { 
       "color": "#00FF00" 
      }, 
      { 
       "lat": "37.9873840", 
       "lon": "23.7604100" 
      }, 
      { 
       "lat": "37.9878040", 
       "lon": "23.7605670" 
      }, 
      { 
       "lat": "37.9882590", 
       "lon": "23.7607340" 
      } 
     ], 
     "path2": [ 
      { 
       "color": "#FF0000" 
      }, 
      { 
       "lat": "37.9882590", 
       "lon": "23.7607340" 
      }, 
      { 
       "lat": "37.9884690", 
       "lon": "23.7598760" 
      } 
     ] 
    } 
] 
} 

我怎麼能看到多少路(PATH0,PATH1,..)陣列我一定在裏面的Javascript waypoints? 使用obj.waypoints.length將返回0.

謝謝。

回答

1

在一個現代的瀏覽器,您可以用Object.keys

var nbpaths = Object.keys(obj.waypoints[0]).length; 

對於IE8的兼容性,可以算這樣的:

var nbpaths = 0; 
for (var key in obj.waypoints[0]) nbpaths++; 
+0

感謝您的回答,但你的代碼返回1,而不是3 –

+0

我沒有看到你的對象是在一個數組中。修正(添加[0])。 –