我有ol結構作爲html,我想從中創建JSON,但我的代碼不會創建我需要的JSON。任何人都可以幫我解決它嗎?如何創建從深li結構的json輸出
我需要這樣的
[
{"en":"Menu1","enlink":"#enlink1","tr":"Menü 1","trlink":"#trlink1","data":[
{"en":"Menu1-1","enlink":"#enlink1-1","tr":"Menü 1-1","trlink":"#trlink1-1","data":[
{"en":"Menu1-1-1","enlink":"#enlink1-1-1","tr":"Menü 1-1-1","trlink":"#trlink1-1-1"},
{"en":"Menu1-1-2","enlink":"#enlink1-1-2","tr":"Menü 1-1-2","trlink":"#trlink1-1-2"}
]},
]},
{"en":"Menu2","enlink":"#enlink2","tr":"Menü 2","trlink":"#trlink2","data":[
{"en":"Menu2-1","enlink":"#enlink2-1","tr":"Menü 2-1","trlink":"#trlink2-1"},
{"en":"Menu2-1","enlink":"#enlink2-1","tr":"Menü 2-1","trlink":"#trlink2-1"}
]},
{"en":"Menu3","enlink":"#enlink3","tr":"Menü 3","trlink":"#trlink3"}
]
而且我的樣本代碼創建JSON ..
var buildJson = function (root){
\t if(!root){
\t \t root='#domenu-en';
\t }
\t var result = [];
\t $(' ol > li ',root).each(function() {
\t \t if($(this).children("ol").length){
\t \t \t result.push({"en":$(this).attr("data-en"),"data":buildJson($(this))});
\t \t \t //return false;
\t \t } else{
\t \t \t result.push({"en":$(this).attr("data-en")});
\t \t }
\t });
return result;
}
$('#results').val(JSON.stringify(buildJson()))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="domenu-en">
<ol>
\t <li data-enlink="#enlink1" data-en="Menu1" data-trlink="#trlink1" data-tr="Menü 1">
\t \t <ol>
\t \t \t <li data-enlink="#enlink1-1" data-en="Menu1-1" data-trlink="#trlink1-1" data-tr="Menü 1-1">
\t \t \t \t <ol>
\t \t \t \t \t <li data-enlink="#enlink1-1-1" data-en="Menu1-1-1" data-trlink="#trlink1-1-1" data-tr="Menü 1-1-1">
\t \t \t \t \t </li>
\t \t \t \t \t <li data-enlink="#enlink1-1-2" data-en="Menu1-1-2" data-trlink="#trlink1-1-2" data-tr="Menü 1-1-2">
\t \t \t \t \t </li>
\t \t \t \t </ol>
\t \t \t </li>
\t \t </ol>
\t </li>
\t <li data-enlink="#enlink2" data-en="Menu2" data-trlink="#trlink2" data-tr="Menü 2">
\t \t <ol>
\t \t \t <li data-enlink="#enlink2-1" data-en="Menu2-1" data-trlink="#trlink2-1" data-tr="Menü 2-1">
\t \t \t </li>
\t \t \t <li data-enlink="#enlink2-1" data-en="Menu2-1" data-trlink="#trlink2-1" data-tr="Menü 2-1">
\t \t \t </li>
\t \t </ol>
\t </li>
\t <li data-enlink="#enlink3" data-en="Menu3" data-trlink="#trlink3" data-tr="Menü 3">
\t </li>
</ol>
</div>
<textarea id="results" style=" height: 279px;"></textarea>
感謝您的傑出貢獻者@Thomas van den Berg,但每次我們再次調用函數時,都會生成其他對象。在結果我有更大的JSON在那裏shoıuld是一個** Menu1-1-1 **,但在此代碼和我的不同孩子生成4個相同的項目。 '$('ol> li',root).each(function()'也可以接觸到子li,我們必須打斷這個過程以達到子li。 –
很高興聽到你找出問題所在 – Thomas