WouldBeNerd
WouldBeNerd

Reputation: 687

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.

Upvotes: 6

Views: 9421

Answers (3)

Debojyoti Chatterjee
Debojyoti Chatterjee

Reputation: 378

If the contents of your file are just key value pair, you can just keep it in a JSON file and require it in your JS file.

For example: If you filename is someConfig.json

{
    "key1": "value1",
    "key2": {
        "label1": "value2",
        "label2": "value3"
    }
}

Now in your js file you can just do the following:

const myJSONFile = require("./someConfig.json");

console.log(myJSONFile.key2.label2); // value3

Upvotes: 0

Yash
Yash

Reputation: 182

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

Upvotes: 2

Daniel
Daniel

Reputation: 18672

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.

Upvotes: 6

Related Questions