Reputation: 2520
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.
Upvotes: 3
Views: 23017
Reputation: 6228
Of course, the first thing you must transform the json string into js object. by use JSON.parse()
(IE6\7 not support) or include the Crockford's JSON2 parser in order to support it on IE < 8.
var obj = JSON.parse(jsonstr);
// loop the obj to find out what you want
Or another way, you can try to use some lib like jsonSelect (CSS-like selectors for JSON.) or something like JSONPath, then you can easy to manipulate your data like:
var reslut = JSONSelect.match('css selector', obj);
Upvotes: 0
Reputation: 2246
This is more or less the code you are looking for:
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]);
}
}
Assuming you are using jQuery. You can parse the JSON with whatever library you want. Just avoid eval()
, which opens your site to XSS vulnerabilities.
Upvotes: 0
Reputation: 35399
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 */
Upvotes: 18