簡體   English   中英

json數組中的項數

[英]Number of items in a json array

尋找一個簡單的JS來計算.json文件中的項目數(每個項目代表,在這種情況下,一張Instagram照片被拉入網絡應用程序;我想計算照片的數量)。 因此,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文件並計算項目數。 完全迷失在哪里開始。

將JSON字符串解析為對象並像使用JavaScript中的任何其他對象一樣使用它:

var o = JSON.parse(jsonstring);

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

這或多或少是您正在尋找的代碼:

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]);
    }
}

假設您正在使用jQuery。 您可以使用您想要的任何庫來解析JSON。 只需避免使用eval() ,這會將您的網站打開到XSS漏洞。

當然,首先必須將json字符串轉換為js對象。 通過使用JSON.parse() (IE6 \\ 7不支持)或包含Crockford的JSON2解析器 ,以便在IE <8上支持它。

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

或者另一種方式,您可以嘗試使用一些類似jsonSelect (類似於JSON的類似CSS的選擇器)或類似JSONPath之類的 ,然后您可以輕松地操作您的數據,如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM