I am have some JSON that I want to turn in to a bulleted list. At each level there is a name field and a children field (apart from at the lowest level). I have tried using recursion to do it but I have run in to a problem. Only the first child is displayed at all but the last level. I have a feeling that some of my recursive calls might not be returning properly. Here is the code I have so far:
function load_menu(){
json_text=ajax_get("example.json");
json_tree=JSON.parse(json_text);
write_menu(json_tree.children,document.getElementById("level1"));
}
function write_menu(json,element){
for(i=0;i<json.length;i++){
var listitem=document.createElement("li");
element.appendChild(listitem);
var listitemtext=document.createElement("span");
listitem.appendChild(listitemtext);
listitemtext.innerText=json[i].name;
if(json[i].children){
listitemtext.setAttribute("onclick","toggle(this);");
var sublist=document.createElement("ul");
listitem.appendChild(sublist);
write_menu(json[i].children,sublist);
};
};
}
I end up with a tree that looks like this:
Level 1,1
Level 2,1
Level 3,1
Level 3,2
It should look like this:
Level 1,1
Level 2,1
Level 3,1
Level 3,2
Level 2,2
Level 1,2
Level 2,3
I have checked through my JSON and it seems to be ok so I guess there must be a problem with the recursion somewhere. Can anyone help me out here?
iset to0would be less thanjson.lengthalways so it will only ever go once, no?for (var i...instead offor (i.... The function may reuse the sameiwhen you recurse like this.i, it will be reseti = 0