2017-03-29 4 views
1

以下の作品が、変換する際、this jsFiddle上の出力を参照してくださいいくつかの<li>を残していると我々はすべてのネストされたリストノードをjsonに変換する方法は?

JSそれは

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> 

いくつかのノードを除外されていることがわかります

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

正しく理解していれば、出力にCalcioがないと言うことになります。

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

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

にあなただけのアウト配列の出力に最初の項目を、それを求めていた。

あなたが変更する必要があります。配列全体を表示したい。

+0

ああ、ありがとうございます! –

+1

ねえ、問題ない、幸運 –

関連する問題