Home > front end >  Trying to parse JSON
Trying to parse JSON

Time:11-19

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);
});

CodePudding user response:

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

CodePudding user response:

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);
});

CodePudding user response:

SyntaxError: Unexpected token  in JSON at position 0 must be a formatting issue of some kind because it has to do with parsing tokens.

By analyzing the error message you provided, we can inspect that between the words token and in there is an invisible character called a ZERO WIDTH NO-BREAK SPACE. See this unicode character inspector for further details: inspector for [token  in].

If you remove that character, that might fix your formatting problem.

Below is a codesandbox you can fork and try out

Here's a link to a codesandbox with attempt to reproduce the invalid json error.

Here's a link to a codesandbox with an attempt to illustrate a working GET request sending data from a parsed json file.

Without further information, it will be difficult to narrow down your problem further. Goodluck!

CodePudding user response:

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.

  • Related