Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate JSON object with jquery

Tags:

json

jquery

Why isn't the following working, inside a loop it never prints the url when myJSON is empty or not.

$.each($.parseJSON(myJSON), function(key,value){
    alert(value.url);
});

for this JSON structure:

[{"host":"foo","url":"bar"},{"host":"foos","url":"bars"}]

Edit: $.each is inside a loop which has instances/iterations where myJSON is empty if that makes a difference.

like image 545
el_pup_le Avatar asked Nov 26 '11 07:11

el_pup_le


People also ask

How to loop JSON object in jQuery?

Review a simple jQuery example to loop over a JavaScript array object. var json = [ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $. each(json, function(idx, obj) { alert(obj. tagName); });

How do I iterate an array of objects in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How to loop data in jQuery?

jQuery Code:each(myArray, function (index, value) { console. log(index+' : '+value); }); Output: So here is the output which displays index and values, by a loop through arrays.

How do you iterate through Ajax response?

$. ajax({ type: "POST", url: "/Customers/GetCustomer", data: { Id: 1 }, dataType: 'json', success: function (response) { for (var i = 0; i < response. CustomerList.


1 Answers

This works for me.

var myJSON = '[{"host":"foo","url":"bar"},{"host":"foos","url":"bars"}]';

$.each($.parseJSON(myJSON), function(key,value){
    alert(value.url);
});
like image 179
Dogbert Avatar answered Oct 10 '22 06:10

Dogbert