【发布时间】:2020-04-08 16:54:37
【问题描述】:
我正在尝试编写一个函数,它将文本文件作为输入并将其转换为下面的 JSON 树格式,以便我可以在我的 d3.js 项目中使用它。
文本文件很简单:以'b'开头的每一行代表一个袋子,后面的整数是袋子的编号。每个包都包含节点。
所以第一行是带有节点 1 和 2 的包 1。 不包含 b 的线表示袋子之间的链接。例如,包 1 指向包 2。
示例输入:
b 1 1 2 3
b 2 2 3 4
b 3 4 5 6
1 2
1 3
预期输出:
const tree = {
id: 1,
name: '1, 2, 3',
vertices: [1, 2, 3],
children: [
{
id: 2,
name: '2, 3, 4',
vertices: [2, 3, 4],
},
{
id: 3,
name: '4, 5, 6',
vertices: [4, 5, 6],
},
],
};
到目前为止的代码(来自 tom 的帮助):
function readTreeInput(evt) {
const file = evt.target.files[0];
const fileReader = new FileReader();
fileReader.onload = function convertTreeToJSON() {
const lines = this.result.split('\n');
const res = {}; let current = res;
for (let line = 0; line < lines.length; line++) {
const textLine = lines[line];
if (textLine.startsWith('c') || textLine.startsWith('s')) continue;
if (textLine.startsWith('b')) {
const bagId = parseInt(textLine[2], 10);
const firstNode = textLine[4];
const secondNode = textLine[6];
const thirdNode = textLine[8];
let vertices;
if (secondNode === undefined) {
vertices = [firstNode];
} else if (thirdNode === undefined) {
vertices = [parseInt(firstNode, 10), parseInt(secondNode, 10)];
} else {
vertices = [firstNode, secondNode, thirdNode];
}
current.id = bagId;
current.name = vertices.join(', '); // bagLabel;
current.vertices = vertices;
current = (current.children = [{}])[0];
}
}
removeExistingTree();
drawTree(res);
};
fileReader.readAsText(file);
}
不太清楚如何从这里开始处理嵌套,有什么建议吗? :)
【问题讨论】:
标签: javascript json file-io