自定义jstree JSON 数据解析成树

custom jstree JSON data parse into tree

我有一个简单的 JSON 数据是这样的:

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

如何让 jsTree 理解这棵树并绘制这棵树?

我需要编写自定义解析函数吗?或者是否有现成的方法。

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/"
      }
    ]
  }
}

以上数据缺少父 "env/child1/env/" 子 "env/child1/env/key1" 1.更正如下: 数据 = [ "env/child1/env/" "env/child1/env/key1", "env/child1/key1", "env/child1/key2", "env/child1/", "env/child2/key1", "env/child2/key2", "env/child2/", "env/" ];

  1. 父级获取子级值的完整代码如下: https://github.com/peterhchen/700-jstree/blob/master/08_PathJSON/0802_PathChild2ParentValueHier.htm