Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  120] [ 1]  / answers: 1 / hits: 20517  / 14 Years ago, tue, september 21, 2010, 12:00:00

Ok, a little new to JSON format..



I have the following JSON string returned from an AJAX call, which firebug actually displays in a tree quite nicely.. however I can't seem to be able to work out how to loop through the content...



{data:{item:[{@id:7,fromMemberID:7,FromMember:david,notificationsType:event,notificationsDesc:A new event (Test Event Thursday, 16 September 2010) has been created.,notificationsDate:16 Sep 2010,notificationsTime:00:02:18},{@id:8,fromMemberID:7,FromMember:david,notificationsType:event,notificationsDesc:A new event (Test Event Thursday, 16 September 2010) has been created.,notificationsDate:16 Sep 2010,notificationsTime:08:26:24}]}}


I have tried to say get a count of items.. alert(data.item.length);
or a loop:



for(i=0; i<data.item.length; i++)
{
alert(data.item[i].FromMember);
}


obviously missing something fundemental...



Any ideas??


More From » json

 Answers
137

You were very close... data is actually a key in your JSON, so you have to refer to your JSON variable to access data.... so you want JSON.data.item[i].FromMember



Here is some full working code:



(function () {
var json = {data:{item:[{@id:7,fromMemberID:7,FromMember:david,notificationsType:event,notificationsDesc:A new event (Test Event Thursday, 16 September 2010) has been created.,notificationsDate:16 Sep 2010,notificationsTime:00:02:18},{@id:8,fromMemberID:7,FromMember:david,notificationsType:event,notificationsDesc:A new event (Test Event Thursday, 16 September 2010) has been created.,notificationsDate:16 Sep 2010,notificationsTime:08:26:24}]}};

var i;
var iLength = json.data.item.length;
for (i = 0; i < iLength; i++) {
alert(json.data.item[i].FromMember);
}
})();​


jsFiddle


[#95557] Friday, September 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;