Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of items in a json array

Looking for a simple bit of JS to count the number of items in a .json file (each item represents, in this case, an instagram photo being pulled into the web app; I want to count the number of photos). Json is structured thusly...

{
 "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", [...]

I just want to loop through the json file and count the number of items. Completely lost on where to begin.

like image 932
Michael C. Avatar asked Dec 02 '22 22:12

Michael C.


1 Answers

Parse the JSON string into an object and use it as you would any other object in JavaScript:

var o = JSON.parse(jsonstring);

alert(o.features.length); /* number of items in features array */
like image 122
Alex Avatar answered Dec 10 '22 12:12

Alex