JSON和Jquery:从嵌套列表元素创建嵌套JSON

我创建了这个jsfiddle: http : //jsfiddle.net/mfnxm/1/

我正在尝试创建此JSON:

[{ "link":"https://stackoverflow.com/about", "title":"About", "nodes":[{ "link":"https://stackoverflow.com/staff", "title":"Staff", "nodes":[{ "link":"https://stackoverflow.com/heads", "title":"Dept Heads" },{ "link":"https://stackoverflow.com/support", "title":"Support" }] },{ "link":"https://stackoverflow.com/location", "title":"Location" }] },{ "link":"https://stackoverflow.com/contact", "title":"Contact" }] 

从这个无序列表:

  

这是迄今为止的javascript( 从这里借来的 ) – 但它并没有为我创建节点元素:

 var out = []; function processOneLi(node) { var aNode = node.children("a:first"); var retVal = { "link": aNode.attr("href"), "title": aNode.text() }; node.find("> .sortable > li").each(function() { if (!retVal.hasOwnProperty("nodes")) { retVal.nodes = []; } retVal.nodes.push(processOneLi($(this))); }); return retVal; } $("#tree ul").children("li").each(function() { out.push(processOneLi($(this))); }); // Do something with data $('#d').text(JSON.stringify(out)); 

我错过了什么? 谢谢!

在每次出现时,用class="sortable" (无句点)替换HTML中的class=".sortable"

你还需要更改$("#tree ul").children("li").each(function()$("#tree > ul > "li").each(function() {以避免冗余处理。

http://jsfiddle.net/mblase75/mfnxm/2/