代码之家  ›  专栏  ›  技术社区  ›  E tom

读取txt文件的行并在JSON文件中组织

  •  2
  • E tom  · 技术社区  · 6 年前

    我有一个文本文件,其中每一行用冒号分隔成4个类别,我想将其放入一个JSON文件中,其中每个类别是JSON文件中相应名称的值。

    例子 data.txt

    Date1:cat1:dog1:bug1
    Date2:cat2:dog2:bug2
    Date3:cat3:dog3:bug3
    

    {
      "Date1": {
        "cat": "cat1",
        "dog": "dog1",
        "bug": "bug1"
      },
      "Date2": {
        "cat": "cat2",
        "dog": "dog2",
        "bug": "bug2"
        ...
      ...
    }
    

    我以前从未使用过JSON,但我认为这就是格式化它的方法。如何使用冒号作为下一个值的标记对每一行进行排序,并使用JavaScript和Node.js以正确的名称将其存储在JSON文件中?

    3 回复  |  直到 6 年前
        1
  •  2
  •   zhangjinzhou    6 年前

    const fs = require("fs");
    const csv = require("csv");
    
    const result = {};
    const keys = ["cat", "dog", "bug"]
    
    // Read data
    const readStream = fs.createReadStream("yourfile.txt");
    
    // Parser
    const parser = csv.parse({ delimiter: ":" });
    
    parser.on("data", (chunk) => {
    result[chunk[0]] = {};
        for(let i = 1; i < chunk.length; i ++) {
            result[chunk[0]][keys[i - 1]] = chunk[i];
        }
    });
    
    parser.on("end", () => {
        console.log(result);
    });
    
    readStream.pipe(parser);
    
        2
  •  1
  •   Pedro Nascimento    6 年前

    import * as fs from 'fs';
    
    /* If you have a large file this is a bad Idea, refer to reading from a stream 
     * From zhangjinzhou's answer
     */
    const file = fs.readFileSync('path/to/data.txt', 'utf8');
    
    const json = file.split(/\n|\r\n/).map(line => {
      const values = line.split(":");
      let obj = {}
    
      obj[values[0]] =  {
        cat: values[1],
        dog: values[2],
        bug: values[3],
      };
    
      return obj
    }).reduce((acc, current) => Object.assign(acc, current), {})
    
        3
  •  1
  •   Rick Gal Koren    6 年前

    使用 RegExp Array#forEach object 相应数据通过:

    const dataFileContent = 
    `Date1:cat1:dog1:bug1
    Date2:cat2:dog2:bug2
    Date3:cat3:dog3:bug3`;
    
    function processData(data) {
      // convert to lines
      const lines = data.match(/[^\r\n]+/g) || [];  
      const object = {};
      
      // iterate over the lines
      lines.forEach(line => {
        const parts = line.split(':');    
        const main = parts.shift();
        const pattern = /^(.*?)(\d+)$/;
        
        // create an object for each main part
        object[main] = {};    
        
        // fill each main part with the sub parts
        parts.forEach(part => {
          const match = part.match(pattern) || [];
          const key = match[1];
          const value = match[2];
                
          if (match) {
            object[main][key] = key + value;
          }
        });
      }); 
      
      return object;
    }
    
    const processedData = processData(dataFileContent);
    console.log(processedData);

    processedData JSON.stringify 并通过以下方式将其保存到文件中:

    const fs = require('fs');
    
    ...
    // processData
    ...
    
    const json = JSON.stringify(processedData);
    fs.writeFile('my_json_file.json', json, 'utf8');
    

    对于较大的文件,请考虑使用 Streams 在Node.js中 @zhangjinzhou .