我正在尝试将带有两列的excel文件转换为Json文件。但是,我想保持层次结构以及如何保持层次结构。例如,从下面的excel文件中,我希望json以这样的方式形成层次结构:“Charles Johnson”是根值,与他相关的大小是5395.同样,在第二行中,“Donald Williams”在“Charles Johnson”下工作,他的大小是3057.依此类推,文件每一行的姓氏将它连接到它的父节点。我想使用.split( - )函数我已经坚持了很长一段时间,直到我最终放弃了:/任何帮助将不胜感激:)
Charles Johnson 4184
Charles Johnson-Donald Williams 8385
Charles Johnson-Donald Williams-Daniel Fertig 428
Charles Johnson-Donald Williams-Daniel Fertig-Lino Walling 1091
Charles Johnson-Donald Williams-Daniel Fertig-Lino Walling-Jim Cooke 318
所需的输出类型:
{
"name": "flare",
"children": [{
"name": "analytics",
"children": [{
"name": "cluster",
"children": [{
"name": "AgglomerativeCluster",
"size": 3938
}, {
"name": "CommunityStructure",
"size": 3812
}, {
"name": "HierarchicalCluster",
"size": 6714
}, {
"name": "MergeEdge",
"size": 743
}]
}
}]]
}
答案 0 :(得分:1)
解析每一行时必须使用递归。假设您总是有两个以制表符分隔的列,并且只有一个根,您的代码可能如下所示:
//example data
var str = "Charles Johnson\t4184\nCharles Johnson-Donald Williams\t8385\nCharles Johnson-Donald Williams-Daniel Fertig\t428\nCharles Johnson-Donald Williams-Daniel Fertig-Lino Walling\t1091\nCharles Johnson-Donald Williams-Daniel Fertig-Lino Walling-Jim Cooke\t318";
var lines = str.split("\n");
var name_ = lines[0].split("\t")[0];
var val_ = lines[0].split("\t")[1];
var obj = {name: name_,
children: [],
value: val_};
//process all lines
for (var i=1;i<lines.length;i++) {
var addr = lines[i].split("\t")[0].split("-");
var val = lines[i].split("\t")[1];
var local_obj = obj;
var recursive_obj;
for (var j=1;j<addr.length;j++) {
recursive_obj = null;
for (var k=0;k<local_obj.children.length;k++) {
if (local_obj.children[k].name==addr[j]) {
recursive_obj=local_obj.children[k];
}
}
if (recursive_obj==null) {
recursive_obj = {name: addr[j],
children: [],
value: null
};
local_obj.children.push(recursive_obj);
}
local_obj=recursive_obj;
}
recursive_obj.value=val;
}
//print a json result
alert(JSON.stringify(obj));