Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - Convert JSON to HTML Tree

I would like to generate an HTML tree (preferably UL-LI) from the JSON example below. Does anyone have a simple, recursive JS function (not a framework) that can handle this specific structure? Thanks for your help!

{ "folder" : [ {
    "title" : "1",
    "folder" : [ {
        "title" : "1.1",
        "folder" : [ {
            "title" : "1.1.1",
        } , {
            "title" : "1.1.2",
        } ]
    } ]
} , {
    "title" : "2",
} ] }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
function to_ul (obj) {
  // --------v create an <ul> element
  var f, li, ul = document.createElement ("ul");
  // --v loop through its children
  for (f = 0; f < obj.folder.length; f++) {
    li = document.createElement ("li");
    li.appendChild (document.createTextNode (obj.folder[f].title));
    // if the child has a 'folder' prop on its own, call me again
    if (obj.folder[f].folder) {
      li.appendChild (to_ul (obj.folder[f].folder));
    }
    ul.appendChild (li);
  }
  return ul;
}

Caveat: No error checking! If a 'title' or 'folder' is missing, the whole thing could blow up.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...