Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda