1

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 becomes 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,[]]"

1 Answer 1

6

I would suggest that you carry on splitting by newline, then recombine 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.

Sign up to request clarification or add additional context in comments.

3 Comments

var data = require(filepath); does the same trick for .json files.
I have already tried to parse it, but then this function drop some objects from array. At the end parsed array become a list of numbers serperated with comma.
I've tried to improve the answer based on your comment, please have a look

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.