el_pup_le
el_pup_le

Reputation: 12179

Iterate JSON object with 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.

Upvotes: 6

Views: 39470

Answers (2)

JN_newbie
JN_newbie

Reputation: 6062

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

$.each(data, function(i, item) {
    alert(data[i].host);
});​

same as with the url.

Upvotes: 9

Dogbert
Dogbert

Reputation: 222148

This works for me.

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

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

Upvotes: 29

Related Questions