自定义jstree JSON数据解析成树

时间:2017-06-29 12:49:24

标签: javascript 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
      • KEY2

我是否需要编写自定义解析函数,或者是否已准备就绪。

2 个答案:

答案 0 :(得分: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/"
      }
    ]
  }
}

答案 1 :(得分:-1)

以上数据缺少子级“ env / child1 / env / key1”的父级“ env / child1 / env /” 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