Reputation: 149
I have a JS file that makes a GET request to an API which then outputs the results to a JSON file. In another JS file, it is to parse the JSON file by reading it, but is running into errors.
SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse (<anonymous>) at C:\Users\user\Desktop\node_express\oncall_api\readjson.js:5:24
JS code
const fs = require('fs');
fs.readFile('log.json', (err, data) => {
if (err) throw err;
let results = JSON.parse(data);
console.log(results);
});
json file
{"personName":["personOne"],"alsoNotifyList":null,"currStart":"2021-03-30T09:00:00-07:00","currEnd":"2021-04-06T09:00:00-07:00"}
I have removed the square brackets manually, but that didn't seem to fix the issue either.
Also if I hardcode the json content into the parse() function it seems to work fine in terms of printing the json in proper format.
let results = JSON.parse('{"personName":["personOne"],"alsoNotifyList":null,"currStart":"2021-03-30T09:00:00-07:00","currEnd":"2021-04-06T09:00:00-07:00"}');
console.log(results.personName) //works and return ['personOne']
Upvotes: 0
Views: 528
Reputation: 64695
Most likely you just need to specify the encoding, so, assuming utf8
:
fs.readFile('log.json', { encoding: 'utf8' }, (err, data) => {
or, if you are on an older version of node,
fs.readFile('log.json', 'utf8', (err, data) => {
Upvotes: 1