2017-06-29 64 views
0

我有一個簡單的JSON數據,是這樣的:定製jstree JSON數據解析成樹

[ 
    "env/child1/env/key1", 
    "env/child1/key1", 
    "env/child1/key2", 
    "env/child1/", 
    "env/child2/key1", 
    "env/child2/key2", 
    "env/child2/", 
    "env/" 
] 

我怎樣才能使jsTree理解這棵樹和繪製樹?

  • ENV
    • child1
      • key1的
      • 鍵2

做我需要編寫自定義分析功能,還是有一個現成的方法。

+0

從jsTree網站來看,你首先需要根據您要建立的樹來實例化DOM。你有這樣的代碼嗎?你把jstree初始化放在$(document).ready中了嗎? – selten98

+0

我沒有準備好任何東西,也許一些指導說明如何做以便我可以開始 ps:我正在使用原始jstree包中的演示文件 – Vagho

+0

您可以更改JSON的外觀嗎?你可以擴展它嗎? – selten98

回答

1
tree = { 
    'core' : { 
     'data' : [ 
     ] 
    } 
} 

data = [ 
    "env/child1/env/key1", 
    "env/child1/key1", 
    "env/child1/key2", 
    "env/child1/", 
    "env/child2/key1", 
    "env/child2/key2", 
    "env/child2/", 
    "env/" 
]; 

minlen = -1; 
picked = ""; 
for(i =0; i<data.length; i++) { 
    if(data[i].length < minlen || minlen == -1) { 
     minlen = data[i].length; 
     picked = data[i]; 
    } 
} 

tree.core.data.push({ "id" : picked, "parent" : "#", "text" : picked }) 
xdata = data 
xdata.splice(xdata.indexOf(picked), 1) 

for(i =0; i<xdata.length; i++) { 
    name = xdata[i] 
    parent = "" 
    if(name.substr(name.length-1,1) == '/') { 
     xname = name.substr(0,name.length-1); 
     parent = xname.substr(0,xname.lastIndexOf("/")+1) 
    } else { 
     parent = name.substr(0,name.lastIndexOf("/")+1) 
    } 
    tree.core.data.push({ "id" : name, "parent" : parent, "text" : name }) 
} 
console.log(tree); 

我遵循替代的JSON格式。

結果:

{ 
    "core": { 
    "data": [ 
     { 
     "id": "env/", 
     "parent": "#", 
     "text": "env/" 
     }, 
     { 
     "id": "env/child1/env/key1", 
     "parent": "env/child1/env/", 
     "text": "env/child1/env/key1" 
     }, 
     { 
     "id": "env/child1/key1", 
     "parent": "env/child1/", 
     "text": "env/child1/key1" 
     }, 
     { 
     "id": "env/child1/key2", 
     "parent": "env/child1/", 
     "text": "env/child1/key2" 
     }, 
     { 
     "id": "env/child1/", 
     "parent": "env/", 
     "text": "env/child1/" 
     }, 
     { 
     "id": "env/child2/key1", 
     "parent": "env/child2/", 
     "text": "env/child2/key1" 
     }, 
     { 
     "id": "env/child2/key2", 
     "parent": "env/child2/", 
     "text": "env/child2/key2" 
     }, 
     { 
     "id": "env/child2/", 
     "parent": "env/", 
     "text": "env/child2/" 
     } 
    ] 
    } 
} 
+0

它的工作,直到我不得不旁邊根ENV創建另一個文件夾 – Vagho