最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js: File reading and putting string as array into array - Stack Overflow

programmeradmin1浏览0评论

I'm working on some project where I need to read some fle and put splitted (with \n - new line) string as array in array. This means that the output from reading file with fs.readFileSync(filepath, 'utf8').split('\n'); is string and I need to convert it into array, but there is problem because I don't know how. There is some example of input data:

[[164,17567,160,[]],[166,8675,103,[]],
[[164,17567,160,[]],[166,8675,103,[]],
[[164,17567,160,[]],[166,8675,103,[]],
[[164,17567,160,[]],[166,8675,103,[]]

I was trying to put it with for loop, but I can't convert it from string into array somehow, the output bees like that:

"[[164,17567,160,[]],[166,8675,103,[]]",
"[[164,17567,160,[]],[166,8675,103,[]]",
"[[164,17567,160,[]],[166,8675,103,[]]",
"[[164,17567,160,[]],[166,8675,103,[]]"

I'm working on some project where I need to read some fle and put splitted (with \n - new line) string as array in array. This means that the output from reading file with fs.readFileSync(filepath, 'utf8').split('\n'); is string and I need to convert it into array, but there is problem because I don't know how. There is some example of input data:

[[164,17567,160,[]],[166,8675,103,[]],
[[164,17567,160,[]],[166,8675,103,[]],
[[164,17567,160,[]],[166,8675,103,[]],
[[164,17567,160,[]],[166,8675,103,[]]

I was trying to put it with for loop, but I can't convert it from string into array somehow, the output bees like that:

"[[164,17567,160,[]],[166,8675,103,[]]",
"[[164,17567,160,[]],[166,8675,103,[]]",
"[[164,17567,160,[]],[166,8675,103,[]]",
"[[164,17567,160,[]],[166,8675,103,[]]"
Share Improve this question asked Mar 19, 2013 at 7:37 user1257255user1257255 1,1718 gold badges26 silver badges55 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

I would suggest that you carry on splitting by newline, then rebine into a single string without the line breaks, then finally parse using JSON.parse.

var lines = fs.readFileSync(filepath, 'utf8').split('\n');
var rawData = '';
for (var l in lines){
    var line = lines[l];
    rawdata += line;
}
var data = JSON.parse('[' + rawdata + ']');

However! It appears (unless it's a typo) that each line there is an extra opening square bracket. These must be deleted before parsing, preferably from the source data if you have any control over it :)

In addition, to make it valid JSON, you will have to wrap the whole thing in "[ ]" as I have shown above.

发布评论

评论列表(0)

  1. 暂无评论