0

我有一个txt文件包含:

{"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"insert","nombre ":1} {"date":"2013/06/26","statement":"select","nombre":4}

如何将文本文件的内容转换为数组,例如:

声明 = [
{“日期”:“2013/06/26”,“声明”:“插入”,“名词”:1},{“日期”:“2013/06/26”,“声明”:“插入","nombre":1}, {"date":"2013/06/26","statement":"select","nombre":4}, ];

我使用 fs 模块节点 js。谢谢

对不起,我会更详细地解释:

我有一个数组:

st = [
    {"date":"2013/06/26","statement":"insert","nombre":1},
    {"date":"2013/06/26","statement":"insert","nombre":5},
    {"date":"2013/06/26","statement":"select","nombre":4},
];

如果我使用此代码:

var arr = new LINQ(st)
    .OrderBy(function(x) {return x.nombre;})
    .Select(function(x) {return x.statement;})
    .ToArray();

我得到了我想要的结果。

插入选择插入

但问题是我的数据在文本文件中。任何建议,再次感谢。

4

4 回答 4

2

如果它是一个小文件,你可能会逃脱这样的事情:

// specifying the encoding means you don't have to do `.toString()`
var arrayOfThings = fs.readFileSync("./file", "utf8").trim().split(/[\r\n]+/g).map(function(line) {
  // this try/catch will make it so we just return null
  // for any lines that don't parse successfully, instead
  // of throwing an error.
  try {
    return JSON.parse(line);
  } catch (e) {
    return null;
  }
// this .filter() removes anything that didn't parse correctly
}).filter(function(object) {
  return !!object;
});

如果它更大,您可能需要考虑使用 npm 上的许多模块中的任何一个来逐行读取它,以从流中使用行。

想看看如何使用流来做到这一点?让我们看看我们如何使用流来做到这一点。这不是一个实际的例子,但无论如何它很有趣!

var stream = require("stream"),
    fs = require("fs");

var LineReader = function LineReader(options) {
  options = options || {};
  options.objectMode = true;

  stream.Transform.call(this, options);

  this._buffer = "";
};
LineReader.prototype = Object.create(stream.Transform.prototype, {constructor: {value: LineReader}});

LineReader.prototype._transform = function _transform(input, encoding, done) {
  if (Buffer.isBuffer(input)) {
    input = input.toString("utf8");
  }

  this._buffer += input;

  var lines = this._buffer.split(/[\r\n]+/);

  this._buffer = lines.pop();

  for (var i=0;i<lines.length;++i) {
    this.push(lines[i]);
  }

  return done();
};

LineReader.prototype._flush = function _flush(done) {
  if (this._buffer.length) {
    this.push(this._buffer);
  }

  return done();
};

var JSONParser = function JSONParser(options) {
  options = options || {};
  options.objectMode = true;

  stream.Transform.call(this, options);
};
JSONParser.prototype = Object.create(stream.Transform.prototype, {constructor: {value: JSONParser}});

JSONParser.prototype._transform = function _transform(input, encoding, done) {
  try {
    input = JSON.parse(input);
  } catch (e) {
    return done(e);
  }

  this.push(input);

  return done();
};

var Collector = function Collector(options) {
  options = options || {};
  options.objectMode = true;

  stream.Transform.call(this, options);

  this._entries = [];
};
Collector.prototype = Object.create(stream.Transform.prototype, {constructor: {value: Collector}});

Collector.prototype._transform = function _transform(input, encoding, done) {
  this._entries.push(input);

  return done();
};

Collector.prototype._flush = function _flush(done) {
  this.push(this._entries);

  return done();
};

fs.createReadStream("./file").pipe(new LineReader()).pipe(new JSONParser()).pipe(new Collector()).on("readable", function() {
  var results = this.read();

  console.log(results);
});
于 2013-06-27T10:41:58.723 回答
2

没有理由不自己做文件解析器。这适用于任何大小的文件:

var fs = require('fs');

var fileStream = fs.createReadStream('file.txt');

var data = "";

fileStream.on('readable', function() {
  //this functions reads chunks of data and emits newLine event when \n is found
  data += fileStream.read();
  while( data.indexOf('\n') >= 0 ){
    fileStream.emit('newLine', data.substring(0,data.indexOf('\n')));
    data = data.substring(data.indexOf('\n')+1);
  }
});

fileStream.on('end', function() {
  //this functions sends to newLine event the last chunk of data and tells it
  //that the file has ended
  fileStream.emit('newLine', data , true);
});

var statement = [];

fileStream.on('newLine',function(line_of_text, end_of_file){
    //this is the code where you handle each line
    // line_of_text = string which contains one line
    // end_of_file = true if the end of file has been reached
    statement.push( JSON.parse(line_of_text) );
    if(end_of_file){
               console.dir(statement);
               //here you have your statement object ready
    }
});
于 2013-06-27T11:10:16.970 回答
0
fs.readFileSync("myfile.txt").toString().split(/[\r\n]/)

这将您的每一行作为一个字符串

然后,您可以使用 UnderscoreJS 或您自己的 for 循环将该JSON.parse("your json string")方法应用于数组的每个元素。

于 2013-06-27T10:36:56.293 回答
0

var arr = fs.readFileSync('mytxtfile', 'utf-8').split('\n')

我认为这是从文本文件创建数组的最简单方法

于 2020-03-08T12:45:16.203 回答