2012-06-27 4 views
2

JS의 간단한 비트가 .json 파일의 항목 수를 세는 것을 찾습니다 (이 경우 각 항목은이 경우 웹 애플리케이션에 인스 트램 사진이 표시됨을 나타냅니다. 사진 수를 센다). Json은 구조적으로 ...json 배열의 항목 수

{ 
"type":"FeatureCollection", 
"features":[ 
    { 
    "type":"Feature", 
    "geometry":{ 
     "coordinates":[ 
      -79.40916, 
      43.87767 
     ], 
     "type":"Point" 
    }, 
    "properties":{ 
     "longitude":-79.40916, 
     "latitude":43.87767, 
     "title":"", 
     "user":"cmay2400", 
     "id":"176051485697457528_13947894", 
     "image":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_7.jpg", 
     "images":{ 
      "low_resolution":{ 
       "url":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_6.jpg", 
       "width":306, 
       "height":306 
      }, 
      "thumbnail":{ 
       "url":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_5.jpg", 
       "width":150, 
       "height":150 
      }, 
      "standard_resolution":{ 
       "url":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_7.jpg", 
       "width":612, 
       "height":612 
      } 
     }, 
     "description":"Today's ride <span class=\"tag\">#zipcar<\/span>", 
     "instagram_id":"13947894", 
     "likes":1, 
     "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_13947894_75sq_1322267355.jpg" 
    } 
    }, 
    { 
    "type":"Feature", [...] 

단지 json 파일을 반복하고 항목 수를 계산하려고합니다. 어디서부터 시작해야할지 모릅니다.

+3

그렇다면 우리는 어떤 속성을 계산 하시겠습니까? – xandercoded

+1

정확히 어떤 아이템을 계산하려고합니까? – natlee75

+0

JS 객체에 .json 파일을 이미로드 했습니까? –

답변

15

객체에 Parse the JSON string과로 사용 당신은 자바 스크립트의 다른 개체 것입니다 : 당신이 사용하는 가정

var variable = jQuery.parseJSON(stringThatIsStoringJson); 

for(var i=0;i<variable.features.length;i++) { 
    doStuff(variable.features[i]); 

    for(var j=0;j<variable.features[i].geometry.coordinates.length;j++) { 
     doMoreStuff(variable.features[i].geometry.coordinates[j]); 
    } 
} 

:이 코드는 더 또는 덜 찾고있다

var o = JSON.parse(jsonstring); 

alert(o.features.length); /* number of items in features array */ 
0

jQuery. 원하는 라이브러리로 JSON을 파싱 할 수 있습니다. eval()을 피하면 사이트가 XSS 취약점에 노출 될 수 있습니다.

0

물론, json 문자열을 js 객체로 변환해야합니다. 사용 JSON.parse()에 의해 (IE6 \ 7 지원되지 않음) 또는 포함 크록 포드의 JSON2 parserjsonSelect (CSS와 같은 선택기 같은 몇 가지 lib 디렉토리를 사용하는, 당신이 시도 할 수 IE < 8

var obj = JSON.parse(jsonstr); 
// loop the obj to find out what you want 

또는 다른 방법으로 그것을 지원하기 위해 JSON의 경우) 또는 JSONPath과 같이 다음과 같이 데이터를 쉽게 조작 할 수 있습니다.

var reslut = JSONSelect.match('css selector', obj);