简体   繁体   中英

Unexpected token � in JSON at position 0

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']

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) => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM