Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird JSON parsing error using require() in node.js

I have the following JSON:

{
   "request" : {
      "language" : "en",
      "title" : "placeholder",
      "year" : "2014"
   }
}

which I'm trying to parse using the following code:

var json = require('../filename);

Oddly, I receive the SyntaxError

/home/username/code/filename:2
   "request" : {
             ^
SyntaxError: Unexpected token :
(...)

The JSON is perfectly valid according to JSONLint. Am I missing something very obvious?

like image 828
haroba Avatar asked Jan 29 '14 01:01

haroba


3 Answers

It sounds like you made a .js file, not a .json file.
Therefore, it's being parsed as Javascript, not JSON.

like image 50
SLaks Avatar answered Nov 15 '22 13:11

SLaks


require() should not be used for loading JSON files. It is used to load node.js modules only, not data. Loading data depending on an extension was effectively deprecated (see countless discussions about require.extensions).

So the right way to load JSON would be something like this:

JSON.parse(require('fs').readFileSync(__dirname + '/filename', 'utf8'))

like image 9
alex Avatar answered Nov 15 '22 12:11

alex


Bad practice or not, this will failure will also occur on windows if the extension of the file is 'JSON', not 'json'. Just cost me a hour to discover that

like image 1
mark d drake Avatar answered Nov 15 '22 13:11

mark d drake