JSON数组中的项数

3

希望能提供一个简单的JS代码,用于计算.json文件中条目的数量(每个条目代表一张从Instagram拉取到Web应用程序中的照片;我想计算照片的数量)。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文件并计算其中的项数。完全不知道从何开始。


4
那我们也是,你想要统计哪些属性? - Alex
1
你想要计数的确切项目是什么? - natlee75
你已经将 .json 文件加载到 JS 对象中了吗? - Brian Glaz
3个回答

18

将JSON字符串解析为对象,然后像使用JavaScript中的任何其他对象一样使用它:

var o = JSON.parse(jsonstring);

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

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漏洞的攻击。

0

当然,首先你必须将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); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接