javascript - 将文本文件转换为 JSON

标签 javascript json file-io

我正在尝试编写一个函数,它将文本文件作为输入并将其转换为下面的 JSON 树格式,以便我可以在我的 d3.js 项目中使用它。

文本文件非常简单:以“b”开头的每一行代表一个包,后面的整数是包的编号。每个包都包含节点。

所以第一行是包 1,包含节点 1 和 2。 不包含 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);
}

不太确定如何从这里开始处理嵌套,有什么建议吗? :)

最佳答案

有什么问题吗? ;-) 我更喜欢更简单的 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;
}

关于javascript - 将文本文件转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61105920/

相关文章:

javascript - 使用 es6-arrow 函数语法检查数组中是否有两项总和等于给定值

javascript - 如何在谷歌分析中跟踪 iPhone 方向?

JavaScript OR (||) 变量赋值解释

java - 尝试 PUT 方法时出现错误 405 (Jersey/Java) : Method Not Allowed

json - 我如何 Json.decode 联合类型?

python - 加扰的 JSON 字符串

java - FileUtils.iterateFiles 忽略

javascript - 自定义 Accordion 组件不渲染主体元素

c++ - C++从文件中读取对象

c++ - 检查 google-nativeclient 文件系统中是否存在目录?