Reputation: 13
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?
Upvotes: 1
Views: 2377
Reputation: 1073968
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:
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);
Upvotes: 5