我有一个txt文件包含:
{ “日期”: “2013年6月26日”, “声明”: “插入”, “农布雷”:1} { “日期”: “2013年6月26日”, “声明”: “插入”, “农布雷”:1} { “日期”: “2013年6月26日”, “声明”: “选择”, “农布雷”:4}
如何将文本文件的内容转换为数组,如:
陈述= [
{ “日期”: “2013年6月26日”, “声明”: “插入”, “农布雷”:1}, { “日期”: “2013年6月26日”, “声明”: “插入”, “农布雷”:1}, {“date”:“2013/06/26”,“声明”:“选择”,“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();
我得到了我想要的结果。
插入选择插入
但问题是我的数据在文本文件中。 任何建议和再次感谢。
答案 0 :(得分: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);
});
答案 1 :(得分: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
}
});
答案 2 :(得分:0)
fs.readFileSync("myfile.txt").toString().split(/[\r\n]/)
这会使你的每一行成为一个字符串
然后,您可以使用UnderscoreJS或您自己的for循环将JSON.parse("your json string")
方法应用于数组的每个元素。
答案 3 :(得分:0)
var arr = fs.readFileSync('mytxtfile', 'utf-8').split('\n')
我认为这是从文本文件创建数组的最简单方法