I am trying to convert a JSON into an unordered list in jQuery.This is my JSON data.
var myJSON = \"{name:\\\"Director\\\",children:[name:\\\"Exe Director1\\\",n
You can use recursive function as follows. Everytime the function is called it returns a "UL", along with its child "LI".
function generateMenu(data) {
var ul = $("");
$(data).each(function (i, dir) {
var li = $('- ' + dir.name + '
');
ul.append(li);
if (dir.children != null && dir.children.length > 0) {
li.append(generateMenu(dir.children));
}
});
return ul;
};
Use it as :
$("#some-div").append(generateMenu(myJsonData));
The Json is,
var myJsonData = JSON.parse('{"name": "Director","children": [{ "name": "Exe Director1" },{ "name": "Exe Director2" },{"name": "Exe Director3","children": [{ "name": "Sub Director1" },{ "name": "Sub Director2" },{"name": "Sub Director3","children": [{ "name": "Cameraman 1" },{ "name": "Cameraman 2" }]}]}]}');