Skip to content

Instantly share code, notes, and snippets.

@vinothbabu
Created August 10, 2012 13:49
Show Gist options
  • Save vinothbabu/3314317 to your computer and use it in GitHub Desktop.
Save vinothbabu/3314317 to your computer and use it in GitHub Desktop.
Sorting JSON response based on type
<script type="text/javascript">
onerror = function (a, b, c) {
alert([a, b, c]);
};
</script>
<script type="text/javascript">
var x = {
"JsonResult": {
"List": [{
"Subject": "My book report on J. K. Rowling's <u>Harry Potter</u> series.",
"Date": "Jan 25th 2009",
"Type": "Book Report",
"Class": "English"
}, {
"Subject": "My book report on Charles Dickens' <u>Oliver Twist</u> novel.",
"Date": "May 1st 2003",
"Type": "Book Report",
"Class": "English"
}, {
"Subject": "My book report on J. R. R. Tolkien's <u>The Lord of the Rings</u> series.",
"Date": "Aug 7th 2007",
"Type": "Book Report",
"Class": "English"
}, {
"Subject": "The civil war in a nutshell.",
"Date": "Feb 26th 2009",
"Type": "Essay",
"Class": "History"
}, {
"Subject": "How does the republican party manage if we life in a democracy?",
"Date": "Apr 5th 2010",
"Type": "Essay",
"Class": "Government"
}, {
"Subject": "A bogus entry",
"Date": "Jan 1st 2000",
"Type": "Bogus",
"Class": "None"
}, {
"Subject": "Zombie followers don't prove anything.",
"Date": "Nov 2nd 2004",
"Type": "Essay",
"Class": "Religion"
}]
}
};
</script>
<script type="text/javascript">
if (typeof Object.prototype.toSource == 'undefined') {
Object.prototype.toSource = function () {
return (typeof JSON != 'undefined' && typeof JSON.stringify == 'function') ? JSON.stringify(this) : this.toString();
};
}
function sortItems(jsonResponse, paramater) {
var sorted = jsonResponse.List.sort(
function (a, b) {
var nameA = a[paramater].toLowerCase();
var nameB = b[paramater].toLowerCase();
return nameA.localeCompare(nameB);
});
return sorted;
}
function makeRow(ar) {
return "<tr><td>" + ar[0] + "</td><td>" + ar[1] + "</td><td>" + ar[2] + "</td><td>" + ar[3] + "</td></tr>";
}
</script>
<script type="text/javascript">
var mySortedList = sortItems(x.JsonResult, "Subject");
//alert(mySortedList.toSource());
var outTable = "<table>";
outTable += "<tr><th>Subject</th><th>Date</th><th>Type</th><th>Class</th></tr>";
for (var i = 0; i < mySortedList.length; i++) {
outTable += makeRow([mySortedList[i].Subject, mySortedList[i].Date, mySortedList[i].Type, mySortedList[i].Class]);
}
outTable += "</table>";
document.write(outTable);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment