在nodejs中将txt文件转换为json

我有一个.txt由管道分隔数据组成的文件。如下图。


HEADER1|HEADER2|HEADER3

Value1|Value2|Value3

Value4|Value5|Value6

Value7|Value8|Value9

我希望能够从文本文件中返回如下所示的对象数组。


[

  { HEADER1: 'Value1', HEADER2: "Value2", HEADER3: 'Value3' },

  { HEADER1: 'Value4', HEADER2: "Value5", HEADER3: 'Value6' },

  { HEADER1: 'Value7', HEADER2: "Value8", HEADER3: 'Value9' }

]

我怎样才能做到这一点?


撒科打诨
浏览 75回答 3
3回答

芜湖不芜

好吧,简单的方法是这样的:// Raw dataconst raw = `HEADER1|HEADER2|HEADER3Value1|Value2|Value3Value4|Value5|Value6Value7|Value8|Value9`;// Or load raw data from fileconst fs = require('fs');const raw = (fs.readFileSync('file.txt')).toString();// Split data by linesconst data = raw.split('\n');// Extract array of headers and// cut it from dataconst headers = (data.shift()).split('|');// Define target JSON arraylet json = [];// Loop datafor(let i = 0; i < data.length; i++) {&nbsp; // Remove empty lines&nbsp; if(/^\s*$/.test(data[i])) continue;&nbsp; // Split data line on cells&nbsp; const contentCells = data[i].split('|');&nbsp; // Loop cells&nbsp; let jsonLine = {};&nbsp; for(let i = 0; i < contentCells.length; i++) jsonLine[headers[i]] = contentCells[i];&nbsp; // Push new line to json array&nbsp; json.push(jsonLine);}// Resultconsole.log(json);例子在这里

慕村9548890

看看csv2json。您可以使用管道作为自定义分隔符

喵喔喔

一个名为readline的核心模块将是最好的选择const fs = require('fs');const readline = require('readline');async function processLineByLine() {&nbsp; const fileStream = fs.createReadStream('input.txt');&nbsp; const rl = readline.createInterface({&nbsp; &nbsp; input: fileStream,&nbsp; &nbsp; crlfDelay: Infinity&nbsp; });&nbsp; // Note: we use the crlfDelay option to recognize all instances of CR LF&nbsp; // ('\r\n') in input.txt as a single line break.&nbsp; const finalResult = [];&nbsp; let keys = [];&nbsp; let i = 0;&nbsp; for await (const line of rl) {&nbsp; &nbsp; &nbsp;//Extract first line as keys&nbsp; &nbsp; &nbsp;if(i === 0) keys = line.split('|');&nbsp; &nbsp; &nbsp;else {&nbsp; &nbsp; &nbsp; &nbsp; const lineArray = line.split('|');&nbsp; &nbsp; &nbsp; &nbsp; const result = keys.reduce((o, k, i) => ({...o, [k]: lineArray[i]}), {});&nbsp; &nbsp; &nbsp; &nbsp;// Or try&nbsp; &nbsp; &nbsp; &nbsp;// result = Object.assign(...keys.map((k, i) => ({[k]: lineArray[i]})));&nbsp; &nbsp; &nbsp; // Or&nbsp; &nbsp; &nbsp; // let result = {};&nbsp; &nbsp; &nbsp; // keys.forEach((key, i) => result[key] = lineArray[i]);&nbsp; &nbsp; &nbsp; &nbsp; finalResult.push(result);&nbsp; &nbsp; &nbsp; &nbsp; console.log(result);&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;i++;&nbsp; }&nbsp; return finalResult;}processLineByLine();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript