Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require .json file with module.exports in nodeJS

im used to creating .json files this way

module.exports = [
{"year":2007,"month":1,"startDate":"2007-01-01","endDate":"2007-01-31"},
{"year":2007,"month":2,"startDate":"2007-02-01","endDate":"2007-02-28"},
{"year":2007,"month":3,"startDate":"2007-03-01","endDate":"2007-03-31"},
]

I then require them like this.

var dates = require('./JSON/dates.json');

this has always worked in the past when i was working with nodejs and grunt to build websites. But now im using nodeJS to create a server app i get this message

SyntaxError: G:\Navision Reports\JS ReportServer\JSON\dates.json: Unexpected token message. I dont understand what's going on. It is working perfectly with .js files.

Please anyone knows why this no longer works? I know i could have a json object if i just remove var dates = require('./JSON/dates.json'); and make the file into one json object, but I'd really rather not reorganise all this data.

like image 677
WouldBeNerd Avatar asked Mar 15 '23 17:03

WouldBeNerd


2 Answers

This isn't valid JSON file, you can check in any code formatter that it has syntax errors:

module.exports = [
{"year":2007,"month":1,"startDate":"2007-01-01","endDate":"2007-01-31"},
{"year":2007,"month":2,"startDate":"2007-02-01","endDate":"2007-02-28"},
{"year":2007,"month":3,"startDate":"2007-03-01","endDate":"2007-03-31"},
]

Please format your JSON in valid way and then require it or change dates.json to dates.js.

If you save file as .json you don't have to use module.exports, you actually can't, because node has built-in support for requiring .json files. You don't even have to use JSON.parse.

like image 163
Daniel Kmak Avatar answered Mar 19 '23 22:03

Daniel Kmak


I think you need to save your file as *.js

require('./JSON/dates.js');

works fine.

Because with module.exports its not a well formed JSON any more; it is javascript

like image 35
Yash Avatar answered Mar 19 '23 23:03

Yash