如何将所有嵌套列表节点转换为json?

时间:2017-03-29 19:02:57

标签: javascript jquery json

以下有效,但转换后会留下一些<li>,请参阅this jsFiddle上的输出,我们会看到它会留下一些节点

HTML

<div id="tree">
  <ul class="sortable">
     <li>Pallacanestro
         <ul class="sortable">
             <li>Dinamo
                 <ul class="sortable">
                     <li>Logan</li>
                 </ul>
             </li>
         </ul>
     </li>
    <li>Calcio
        <ul class="sortable">
            <li>Milan
                <ul class="sortable">
                    <li>Goal</li>
                </ul>
            </li>
        </ul>
    </li>
  </ul>
</div>
<div id="d" style="margin-top: 40px; padding-top: 20px;">Output:<br><br><pre></pre></div><br><pre></pre></div>

JS

var out = [];
function processOneLi(node) {       
    var aNode = node.contents().first();
    var retVal = {
        "name": aNode.text().trim(),
        "url": aNode.attr("href")
    };
    node.find("> .sortable > li").each(function() {
        if (!retVal.hasOwnProperty("children")) {
            retVal.children = [];
        }
        retVal.children.push(processOneLi($(this)));
    });
    return retVal;
}
$("#tree > ul > li").each(function() {
    out.push(processOneLi($(this)));
});

$('#d pre').text(JSON.stringify(out[0], null, 2));

输出缺少<li>

{
  "name": "Pallacanestro",
  "children": [
    {
      "name": "Dinamo",
      "children": [
        {
          "name": "Logan"
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

如果我正确理解你,你会说你在输出中缺少Calcio。

您需要更改:

$('#d pre').text(JSON.stringify(out[0], null, 2));

$('#d pre').text(JSON.stringify(out, null, 2));

你只是要求它输出数组中的第一项。你想要显示整个数组。

相关问题