Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!