Thursday, October 4, 2012

jQuery $.getJSON is NOT Jason from Friday the 13th

Although at times $.getJSON can certainly seem like a maniacal mass murderer to those not used to working with it.
Tips for the unwary and clues for the clueless.
When iterating through data returned by $.getJSON, make sure you know when to refer to the subscripts as numeric arrays as opposed to associative arrays.
EG: From a typical json file:


{
"customers": [
{ "id":1,"name":"John Doe" },
{ "id":2,"name":"Sand Wich" },
{ "id":3,"name":"Meanmissus Jones" },
{"id":4,"name":"Hung Lo"},
{"id":5,"name":"Cardin Naal"}
],
"magazines": [
{ "id":1,"name":"Field and Wild","rate":29.99 },
{ "id":2,"name":"Car and Driven","rate":34.95},
{ "id":3,"name":"Unpopular Scientists","rate":42.95 },
{"id":4,"name":"TV Lied","rate":19.99},
{"id":5,"name":"Readers Indigestion","rate":24.99}
],
"subscriptions": 
{"1": [{"id":2,"startdate":"01/01/2012","enddate":"01/01/2013"},
{"id":4,"startdate":"01/01/2012","enddate":"01/01/2014"},
{"id":5,"startdate":"01/01/2011","enddate":"01/01/2013"}
],
"2": [{"id":1,"startdate":"01/01/2011","enddate":"01/01/2013"},
{"id":3,"startdate":"01/01/2012","enddate":"01/01/2015"},
{"id":5,"startdate":"01/01/2011","enddate":"01/01/2012"}
],
"3": [{"id":2,"startdate":"09/01/2011","enddate":"09/01/2012"},
{"id":3,"startdate":"01/01/2012","enddate":"01/01/2014"},
{"id":4,"startdate":"06/01/2010","enddate":"06/01/2012"}
],
"4": [
{"id":4,"startdate":"01/01/2012","enddate":"01/01/2015"}
],
"5": [{"id":1,"startdate":"01/01/2011","enddate":"01/01/2013"},
{"id":2,"startdate":"06/01/2011","enddate":"06/01/2013"}
]}

}


Say you're in a for loop, using i as the iterator to run through subscriptions, and starting i at 1: data.subscriptions[i] does NOT equal data.subscriptions[1], as in the 2nd subscript of a numeric array. It equals data.subscriptions['1'], with '1' (variable i's value) being the key, and the 3 groups of subscription data following it as the value (itself a numeric array in this case). For magazines and customers, however, magazines[i] would equate to magazines[1], the 2nd subscript (Car and Driven). In iterating through subscriptions, we're first going through the associate array from keys 1 through 5. Each of those contains a numeric array. If i2 starts at 0 for going through that array and i still ='1': data2.subscriptions[i][i2].id refers to data2.subscriptions['1'][0].id, the first subscript under key '1', with a value of 2. data2.subscriptions['1'][1].id equals 4, data2.subscriptions['1'][2].startdate = "01/01/2011", etc, etc.

No comments:

Post a Comment