Thursday, 25 May 2017

JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0`

I'm writing my first application in Node.js. I am trying to read some data from a file where the data is stored in the JSON format.

I get this error:

SyntaxError: Unexpected token  in JSON at position 0

at Object.parse (native)

Here is this part of the code:

//read saved addresses of all users from a JSON file
fs.readFile('addresses.json', function (err, data) {
    if (data) {
        console.log("Read JSON file: " + data);
        storage = JSON.parse(data);

Here is the console.log output (and I checked the .json file itself, it's the same):

Read JSON file: {

    "addresses": []

}

That seems to me like a correct JSON. Why does JSON.parse() fail then?



via K48

No comments:

Post a Comment