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?
It sounds like you made a .js
file, not a .json
file.
Therefore, it's being parsed as Javascript, not JSON.
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'))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With