我正在尝试编写一个将文本文件作为输入并将其转换为下面的JSON树格式的函数,以便可以在d3.js项目中使用它。
文本文件非常简单:以'b'开头的每一行代表一个袋子,以下整数是袋子的编号。每个袋子都包含节点。
因此,第一行是具有节点1和2的bag 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],
},
],
};
到目前为止的代码(汤姆的帮助):
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);
}
不太确定如何从这里开始照顾嵌套,有什么建议吗? :)
答案 0 :(得分:1)
有什么问题吗? ;-)我更喜欢textLine.split(''),但大部分代码都保持不变。并假设FileReader在这里不起作用。
var result = document.createElement('PRE');
result.innerText = x = JSON.stringify(
convertTreeToJSON.call({ result: 'b 1 1 2\nb 2 2 3\nb 3 4 3\nb 4 5 4\n1 2\n2 3\n3 4' })
, null, 1)
.replace(/\[\n\s+(\d+),\n\s+(\d+)\n\s+]/g, '[$1, $2]')
.replace(/\[\n\s+/g, '[').replace(/}\n\s+\]/g, '}]');
document.body.appendChild(result);
function convertTreeToJSON (x) {
const lines = this.result.split('\n');
const edges = [];
const treeBags = [];
const listOfIds = [];
var res = {}; var current;
for (let line = 0; line < lines.length; line++) {
const textLine = lines[line];
if (textLine.startsWith('c') || textLine.startsWith('s')) return;
if (textLine.startsWith('b')) {
const bagId = parseInt(textLine[2]);
let bagLabel;
let vertices;
const firstNode = textLine[4];
const secondNode = textLine[6];
const thirdNode = textLine[8];
if (secondNode === undefined) {
vertices = [firstNode];
} else if (thirdNode === undefined) {
vertices = [parseInt(firstNode), parseInt(secondNode)];
} else {
vertices = [firstNode, secondNode, thirdNode];
}
if (res.id === undefined) {
current = res;
} else {
current = res.children[res.children.push({}) - 1];
}
current.id = bagId;
current.name = vertices.join(', '); // bagLabel;
current.vertices = vertices;
if (current == res) current.children = [];
}
}
return res;
}