Creating a Hierarchical Dropdown List from JSON Data Using jQuery

Recently I ended up with a project requirement that needed to build dropdown menus from external data. Because the project ran offline, databases and backend programming were out of the question, so I had decided to use JSON as the storage medium for the package data as well as the manifest of all packages. The challenge would be both coming up with a JSON format for storing hierarchical data, and being able to parse it in Javascript. Here’s ultimately what I came up with:

External JSON file:
{
"name": "Example Package",
"author": "Chris Bartek",
"contents": [
{
"title": "Menu 1",
"href": "menu1.html",
"children": [
{
"title": "Submenu 1",
"href": "submenu1.html"
},
{
"title": "Submenu 2",
"href": "submenu2.html"
}]
},
{
"title": "Menu 2",
"href": "menu2.html",
"children": [
{
"title": "Submenu 1",
"href": "submenu1.html"
},
{
"title": "Submenu 2",
"href": "submenu2.html",
"children": [
{
"title": "Subsubmenu 1",
"href": "subsubmenu1.html"
}]
}
]
}
]
}

Javascript/jQuery:
$.getJSON('package.json', function(data){
var module = [];
$.each(data, function(key, val){
module[key] = val;
});

var ul = $('<ul id="nav"></ul>');
$.each(module.contents, function(key, value){
var func = (function (item, list){
if(item){
if(item.href && item.title){
$(list).append($('<li></li>', {
"html": $('<a></a>', {
"href": item.href,
"html": item.title
})
}));
}
if(item.children && item.children.length){
var sublist = $('<ul></ul>');
for(index in item.children){
func(item.children[index], sublist);
}
$(list).children().last().append($(sublist));
}
}
});
func(value, $(ul));
});
$('nav').html(ul);
});

All that’s left is to hook in a dropdown menu script. I used a pure CSS solution, but a jQuery one would work, too. Hope this helps someone out there.

Leave a Reply

Your email address will not be published. Required fields are marked *