Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through a json object in ajax response [duplicate]

I am new to json so i am getting a json reponse from my ajax call

now i am stuck with looping the json object

here is my json

 {
    "0": {
        "image": "http://test.com/systems.jpg",
        "anchor_tag_link": "http://test.com/1",
        "title": "Oct-Dec-2013"
    },
    "1": {
        "image": "http://test.com/energy.jpg",
        "anchor_tag_link": "http://test.com/1",
        "title": "July-Sept-2013"
    },
    "pages": 2
}

Can anyone help

like image 523
Dev Avatar asked Jun 02 '26 23:06

Dev


2 Answers

You can use a for-in loop as follows:

var obj = {
  "0": {
    "image": "http://test.com/systems.jpg",
    "anchor_tag_link": "http://test.com/1",
    "title": "Oct-Dec-2013"
},
"1": {
    "image": "http://test.com/energy.jpg",
    "anchor_tag_link": "http://test.com/1",
    "title": "July-Sept-2013"
},
"pages": 2
}

for(var prop in obj) {
    var item = obj[prop];
    console.log(item);
}

Be aware that you will get the items in your log because you will get the pages property in addition to the numeric properties.

like image 101
Dave Avatar answered Jun 04 '26 12:06

Dave


Save your JSON response in a variable

var variable = {
    "0" : {
        "image" : "http://test.com/systems.jpg",
        "anchor_tag_link" : "http://test.com/1",
        "title" : "Oct-Dec-2013"
    },
    "1" : {
        "image" : "http://test.com/energy.jpg",
        "anchor_tag_link" : "http://test.com/1",
        "title" : "July-Sept-2013"
    },
    "pages" : 2
};

Then loop it using jquery

$.each(variable, function(index, value) {
    alert(value.image);
    alert(value.anchor_tag_link);
});
like image 24
Gowtham Selvaraj Avatar answered Jun 04 '26 12:06

Gowtham Selvaraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!