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

82
Visualizações
Trying to parse JSON

I'm a complete beginner at node.js and trying to figure out how to send the contents of a JSON-object using REST. My code only results in an error saying "SyntaxError: Unexpected token  in JSON at position 0". I have used an online validator to see that the JSON is corrent. What is the issue?

// GET courses
const fs = require('fs');

app.get('/api/courses', function(req, res) {
  var rawdata = fs.readFileSync('miun-db.json');
  var data = JSON.parse(rawdata);
  res.send(data.courses);
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The data inside of your file is not formatted properly. Verify that miun-db.json is properly formatted before attempting to parse.

about 4 years ago · Juan Pablo Isaza Relatório

0

The issue is that your file is not properly formatted, check this out Working with JSON.

Also you can just import the JSON file and use it without fs.

import miunDb from './miun-db.json';

app.get('/api/courses', function(req, res) {
  res.send(miunDb.courses);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

According to the fs.readFileSync docs you can pass options to the function.

fs.readFileSync(path[, options])

If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.

Since you don't pass any options you get a buffer and not the string content of the file.

Either you pass encoding to the function, e.g.

var rawdata = fs.readFileSync('miun-db.json', {encoding:'utf8'});
var data = JSON.parse(rawdata);

or you convert the buffer to string. E.g.

var rawdata = fs.readFileSync('miun-db.json');
var data = JSON.parse(rawdata.toString('utf8'));

Edit:

Your error message says you have an invalid character which is non printable. Seems like your file starts with a BOM (zero width no-break space (ZWNBSP)).

What happens if you try to remove it?

function stripBOM(content) {
  content = content.toString()
  // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  // because the buffer-to-string conversion in `fs.readFileSync()`
  // translates it to FEFF, the UTF-16 BOM.
  if (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1)
  }
  return content
}

// [...]

var rawdata = fs.readFileSync('miun-db.json', {encoding:'utf8'});
var data = JSON.parse(stripBOM(rawdata));

// [...]

Credit goes to this gist.

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