Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda