【问题标题】:Turning a text file into JSON将文本文件转换为 JSON
【发布时间】: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


    【解决方案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;
    }

    【讨论】:

    • 谢谢。我唯一想要改变的是如果一个节点没有孩子我希望它像上面的输出一样:没有行或数组,所以它只是 id: 4, name: '5, 4',vertices: [ 5, 4] 有没有办法做到这一点?
    • 不用担心,睡一觉,感谢您的帮助:) 文本文件中不以 b 开头的行决定了节点之间的链接。所以包 1 链接到包 2,包 1 也链接到包 3,所以树看起来像这样:imgur.com/wEXc7HX aka 在这种情况下的第一个节点将有 2 个子节点
    • 你可以再玩一次;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多