Search code examples
jsonnode.jsfs

How to read a text file and return it as a JSON object in Node JS?


I have a text file. I need to read the file inside a function and return it as a JSON object. The following is throwing an error "Unexpected token V in JSON at position 0" .

Server.js

fs.readfile('result.txt', 'utf8', function(err,data) {
    if(err) throw err;
    obj = JSON.parse(data);
    console.log(obj);
});

result.txt looks like the following

VO1: 10 5 2

VO2: 5 3 2

I think I cannot use JSON.parse directly. How do I proceed?


Solution

  • Assuming the following:

    Every line is separated by a newline character (\n)

    Every line is separated by a : where the part in front of it is the key and the part behind it is a (space) separated string that should indicate the keys values as an array.

    Below should work for your format:

    fs.readfile('result.txt', 'utf8', function(err,data) {
        if(err) throw err;
        let obj = {};
        let splitted = data.toString().split("\n");
        for (let i = 0; i<splitted.length; i++) {
            let splitLine = splitted[i].split(":");
            obj[splitLine[0]] = splitLine[1].trim();
        }
        console.log(obj);
    });