Skip to content

Instantly share code, notes, and snippets.

@TRex22
Last active August 29, 2015 14:14
Show Gist options
  • Save TRex22/383e97df3d5605d6e533 to your computer and use it in GitHub Desktop.
Save TRex22/383e97df3d5605d6e533 to your computer and use it in GitHub Desktop.
Convert JSON to HTML via Javascript and JQuery
//FROM: http://stackoverflow.com/questions/8324239/generating-html-from-arbitrarily-complex-json-object-in-javascript
jQuery(function($) {
display("Loading the JSON data");
$.ajax({
type: "GET",
url: "/path/to/the/data",
dataType: "JSON",
success: function(data) {
display("Got the data, rendering it.");
$(document.body).append(renderContents(data.contents));
},
error: function() {
display("An error occurred.");
}
});
function renderContentsAsList(contents) {
if (contents && contents.length) {
var index, ul;
// Create a list for these contents
ul = $("<ul>");
// Fill it in
$.each(contents, function(index, entry) {
var li;
// Create list item
li = $("<li>");
// Set the text
li.text(entry.filename);
// Append a sublist of its contents if it has them
if (entry.content) {
li.append(renderContents(entry.content));
}
// Add this item to our list
ul.append(li);
});
// Return it
return ul;
}
}
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment