Bharg
Bharg

Reputation: 321

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?

Upvotes: 1

Views: 15053

Answers (6)

Praveen
Praveen

Reputation: 31

It could be issue with UTF-8 string format, Tried below code and it works

const resultBuffer = fs.readFileSync('result.txt');
const resultData = JSON.parse(resultBuffer.toString().trim());

Upvotes: 2

Nikhil Nayyar
Nikhil Nayyar

Reputation: 409

improving upon @baao answer:

const fs = require("fs")

fs.readFile('.czrc', 'utf8', function (err, data) {
    if (err) {
        console.error(err)
        throw "unable to read .czrc file.";
    }
   const obj = JSON.parse(data)
});

Upvotes: -1

baao
baao

Reputation: 73221

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);
});

Upvotes: 4

Seth Eden
Seth Eden

Reputation: 1162

Thanks to Baao for providing that answer.

As another flavor of solution, if you don't have any ":" for perhaps a list of files you could always code in a key like so:

var data = fs.readFileSync(pathAndFilename);
var testData = {};
var splitList = data.toString().split('\r\n');
for (var i = 0; i < splitList.length; i++) {
     testData['fileNumber' + i.toString()] = splitList[i];
}

Upvotes: 0

Vincent Sch&#246;ttke
Vincent Sch&#246;ttke

Reputation: 4716

You need to parse the text file by yourself. You can use RegExp or some other means to extract the values, create an object out of that and then JSON.stringify it.

Upvotes: -1

kenda
kenda

Reputation: 488

Your result.txt is not valid json.

Valid json would look like this.

{
  "VO1": [10, 5, 2],
  "VO2": [5, 3, 2]
}

Upvotes: -2

Related Questions