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
1 Answer
Reset to default 6I 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.