json数组中的项数

时间:2012-06-27 15:35:55

标签: javascript json

寻找一个简单的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文件并计算项目数。完全迷失在哪里开始。

3 个答案:

答案 0 :(得分:17)

Parse the JSON string到一个对象中并像使用JavaScript中的任何其他对象一样使用它:

var o = JSON.parse(jsonstring);

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

答案 1 :(得分:0)

这或多或少是您正在寻找的代码:

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漏洞。

答案 2 :(得分:0)

当然,首先必须将json字符串转换为js对象。使用JSON.parse()(IE6 \ 7不支持)或包含Crockford的JSON2 parser以便在IE上支持它&lt; 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);