jamesthoo
jamesthoo

Reputation: 65

NodeJs JSON.parse - SyntaxError: Unexpected token u in JSON at position 0

Essentially all I am trying to do is simply parse my JSON file using this code:

var fileName = `./tasks/file-1.json`

fs.readFile(fileName, function(err, data){

    var parsedData = JSON.parse(data);
    console.log(`Entered ${parsedData.fname}`);

});

My file-1.json file looks like this:

{
  "fname": "Test"
}

So for whatever reason the console should log "Entered Test", however it is throwing me the error:

SyntaxError: Unexpected token u in JSON at position 0

I have checked over everything and I'm unsure of where to go from here.

Any help is appreciated!

Upvotes: 1

Views: 1898

Answers (3)

Karthik Ashokkumar
Karthik Ashokkumar

Reputation: 59

Check whether the JSON file exists in the same path you provided.

This one is working bro!

const fs = require('fs')
const fileName = './tasks/file-1.json'

fs.readFile(fileName, function(err, data){
    var parsedData = JSON.parse(data);
    console.log(`Entered: ${parsedData.fname}`);
});

Upvotes: 0

Ricardo Machado
Ricardo Machado

Reputation: 782

Check the encoding of your file.

also try

fs.readFile(fileName, 'utf8', function(err, data){

    var parsedData = JSON.parse(data);
    console.log(`Entered ${parsedData.fname}`);

});

Upvotes: 1

Eren Yatkin
Eren Yatkin

Reputation: 326

Hello I created a simple example. File name must be the exact driectory and your JSON file should not include ;

You can use __dirname gives you the current directory path and path.join combines the given string parameters to understanble path.

Hope this help.

// index.js
const fs = require('fs');
const path= require('path');

const file = fs.readFileSync(path.join(__dirname, 'test.json'));
console.log(JSON.parse(file.toString()).key);
// test.json
{
    "key": "1"
}

Upvotes: 0

Related Questions