How to write an index loop for a json object

I have an image updater. I am loading by JSON the exact same file/partial that show my images.

I would like to write a loop that runs through an index and replaces every image with its equal.

This is the first div in my json object :

[{
  "photo": {
    "position":1,
    "photo_file_size":45465,
    "created_at":"2010-10-05T09:51:13-04:00",
    "updated_at":"2010-10-05T09:52:29-04:00",
    "photo_file_name":"tumblr_l0x861Yc5M1qbxc42o1_400.jpg",
    "is_cropped":true,
    "crop_h":null,
    "photo_content_type":"image/jpeg",
    "id":216,
    "caption":null,
    "crop_w":null,
    "photo_uploaded_at":null,
    "crop_x":null,
    "processing":false,
    "gallery_id":26,
    "crop_y":null
  }
},
...

The next div in that json object would be something like gallery_photos_attributes_1_id .

Update

This is what I got so far.. but the load() method doesn't work correctly. I get a "ONLY GET REQUESTS ALLOWED"

$.getJSON(url, function(data) {
for (var i = 0; i < data.length; i ++) {
  url2 = "/organizations/" + 1 + "/media/galleries/" + 26 + "/edit_photo_captions"
  var image = $("#gallery_photos_attributes_" + i + "_caption");
url_str = image.siblings("img").attr("src").substr(0, str.lastIndexOf("/"));
image.siblings("img").load(url2, image.siblings("img"));
};
})

Answers


Although I'm not 100% I got you right, try this piece of code.

var url = "/organizations/" + organization + "/media/galleries/" + gallery + "/update_photo_index"
$.getJSON(url, function(data) {
  // the outer is an array, so just loop as usual
  for (var i = 0; i < data.length; i++) {
    // fetch something for the current photo
    var caption = $("#gallery_photos_attributes_"+ data[i].photo.id +"_caption");
    // update source
    caption.siblings("img").attr("src","/path/to/images/"+data[i].photo.photo_file_name+"?c="+parseInt(Math.random()*10000));
    // update caption
    caption.html(data[i].photo.caption);
    // and so on...
  }
});

Remember that in JSON "[ ... ]" describes an array whereas "{ ... }" describes an object. With an array you can just loop as with every other javascript array. If you got an object, it's like any other javascript object whose fields are accessible either with object.field or object['field']. So using JSON in javascript is nearly a no-brainer.

Hope that helps.


Need Your Help

OpenCV 3.1 Stitch images in order they were taken

c++ opencv android-ndk opencv-stitching

I am building an Android app to create panoramas. The user captures a set of images and those images

Using SAS X Command with PCFILES server

excel sas enterprise-guide

I have some SAS code that writes out to a specific sheet in an excel workbook. The other sheets have formulas that look to this sheet so the workbook is basically a template that gets populated whe...