tree traversing in json and jquery/html javascript

im traversing a tree in json. the code is working, giving me an output. however its a wrong result. instead of getting the correct tree, im getting a tree where branches are misplaced. for example, a node is coming out to be a child instead of being a sibling. so its a logic error. this is the traversing function pls check it out:

function traverse(node, o) {
            for (var i in o) {
                if(i == "__text" || i == "_href")
                    continue;
                if (o[i] !== null && typeof(o[i])=="object") {
                    if(o[i].__text){ 

                       var ul = $("<ul>").appendTo(node)
                        var node=$('<li>').appendTo(ul)


                        if(o[i]._href){
                           var n = $("<span>").appendTo(node)
                            $(n).text(o[i].__text).attr("href", o[i]._href)
                    }
                        else{
                            $(node).text(o[i].__text)
                        }
    }
                    }
                    traverse(node,o[i]);
                }
                else{
                    var ul = $("<ul>").appendTo(node)
                    if(o[i].__text){
                        var li = $('<li>' + o[i]._text + '</li>').appendTo(ul)
                        if(o[i]._href){
                            var n = $("<span>").appendTo(node)
                            $(n).text(o[i].__text).attr("href", o[i]._href)
                        }

                    }else{
                            $('<li>' + o[i] + '</li>').appendTo(ul)
                    }


                }
            }
        }


Source: json

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.