简体   繁体   中英

Unexpected token in JSON at position 0

I'm trying to read a.json file with fs and parse to a JavaScript object using JSON.parse() function.

const json = JSON.parse(fs.readFileSync('./db.json', (err) => { if (err) throw err; }))
{
  "hello": "world"
}

But I'm getting the following error:

undefined:1 { ^ SyntaxError: Unexpected token in JSON at position 0

Does anyone know what's wrong?

readFileSync returns a Buffer if you don't tell it what encoding to use to convert the file contents to text. If you pass a Buffer into JSON.parse , it'll get converted to string before being parsed. Buffer 's toString defaults to UTF-8.

So there are a couple of possible issues:

  1. The file isn't in UTF-8
  2. It is, but it has a byte order mark (BOM) on it (which is slightly unusual — UTF-8 has a fixed byte order — but there is one defined and sometimes files have it as an indicator they're in UTF-8)

Separately from that, readFileSync doesn't accept a callback (it returns its result or throw an error instead, because it's synchronous — that's what the Sync suffix means in the Node.js API). (If it did have a callback, doing throw err in that callback would be pointless. it wouldn't, for instance, throw an error from the function where you're calling readFileSync .)

If the file isn't UTF-8, tell readFileSync what encoding to use (I suggest always doing that rather than relying on implicit conversion to string later). If it's in (say) UTF-16LE ("UTF-16 little endian"), then you'd do this:

const data = JSON.parse(fs.readFileSync('./db.json', "utf16le"));

If it's in UTF-8 with a BOM: Buffer doesn't remove the BOM when it converts to string, so you end up with what looks like a weird character at position 0 which JSON.parse doesn't like. If that's the case, you can do this:

const UTF8_BOM = "\u{FEFF}";
let json = fs.readFileSync('./db.json', "utf8");
if (json.startsWith(UTF8_BOM)) {
    // Remove the BOM
    json = json.substring(UTF8_BOM.length);
}
// Parse the JSON
const data = JSON.parse(json);

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