1

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?

3
  • What's the content of result.txt? Commented Sep 12, 2016 at 13:04
  • Would be helpful to take a look at result.txt. Commented Sep 12, 2016 at 13:04
  • 1
    You can't, since the .txt file gets imported as a string, iirc. You'll have to write your own parser for the data to be translated to json. Commented Sep 12, 2016 at 13:10

6 Answers 6

4

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting an error with splitLine as unidentified identifier.
So some of the lines don't have a key, a value or a :. Try to add a check before you assign the values to the object @Bharg
2

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

2 Comments

It’s an issue with the file not being JSON or even remotely like JSON.
My text file was JSON and this creates a valid JSON object of that text file.
0

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

2 Comments

Hello, what is the pathAndFilename value?
This would be the full path and file name to the file that you want to read. aka C:\Program Files\MyApp\Configuration\systemConfiguration.txt
-1

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.

Comments

-1

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

Comments

-2

Your result.txt is not valid json.

Valid json would look like this.

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

Comments

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.