Applying Order to JSON Data When Rendering to a Page

It is very convenient to pass JSON data from client to server and between different server-side components. However, JSON data is an inherently unordered data structure and in many cases a developer will want to render a list of items in some specified order.

One way that I found to do so is to append an integer to the keys in your data when generating the JSON data. For example, you might be iterating through a database result set and want to maintain the order in which the result was returned. When adding your keys append ‘_n’ to the string.

Then, when you access the JSON data (with JavaScript, and jquery, and assuming a reference to your JSON data is ‘data’) first get a count of the number of objects in your JSON container:

$counter = 0;

$.each(data, function(key, value) {

? $counter++;

alert(key + ‘: ‘ + eval(value.id));

});

Now we have a count of the number of items in the object and run a for loop using the $counter variable.

for(var $rowCounter = 0; $rowCounter < $counter; rowCounter++) {

? // Access your data using the $rowCounter value

? alert(“row ” + $rowCounter + ” = ” + eval(“data.row_” + $rowCounter));

}

Leave a Reply