Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'd like to generate a tree view of my JSON data. Therefore it would be nice to parse the JSON data into a multi-level (!) unordered HTML list. I found a few plugins but I can't get them to work with my JSON data.

Nice solution would be a call to a function and hand over the json data as parameter. The result could be a multi-level unordered list. I assume that the function has to loop through all the JSON data and write ul and li tags.

Is there a straight forward way to do that?

tia!

PS: Example trees (that work with my JSOn data): http://braincast.nl/samples/jsoneditor/ http://www.thomasfrank.se/downloadableJS/JSONeditor_example.html

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just a quick simple example:

function tree(data) {    
    if (typeof(data) == 'object') {
        document.write('<ul>');
        for (var i in data) {
            document.write('<li>' + i);
            tree(data[i]);            
        }
        document.write('</ul>');
    } else {
        document.write(' => ' + data);
    }
}

jQuery version:

function tree(data) {    
    if (typeof(data) == 'object') {        
        var ul = $('<ul>');
        for (var i in data) {            
            ul.append($('<li>').text(i).append(tree(data[i])));         
        }        
        return ul;
    } else {       
        var textNode = document.createTextNode(' => ' + data);
        return textNode;
    }
}

$(document.body).append(tree(data));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...