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

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

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 Denunciar

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 Denunciar

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 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