如何在nodeJS中使用 module.exports 请求 .json 文件

Wou*_*erd 5 javascript json node.js

我习惯以这种方式创建 .json 文件

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"},
]
Run Code Online (Sandbox Code Playgroud)

然后我像这样要求他们。

var dates = require('./JSON/dates.json');
Run Code Online (Sandbox Code Playgroud)

过去当我使用 Node.js 和 grunt 构建网站时,这一直有效。但现在我使用 nodeJS 创建一个服务器应用程序,我收到此消息

语法错误:G:\Navision Reports\JS ReportServer\JSON\dates.json:意外的令牌消息。我不明白发生了什么事。它与 .js 文件完美配合。

请问有人知道为什么这不再起作用吗?我知道如果我删除 var date = require('./JSON/dates.json'); 我可以有一个 json 对象 并将该文件放入一个 json 对象,但我真的不想重新组织所有这些数据。

Dan*_*mak 6

这不是有效的 JSON 文件,您可以在任何代码格式化程序中检查它是否存在语法错误:

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"},
]
Run Code Online (Sandbox Code Playgroud)

请以有效的方式格式化您的 JSON,然后要求它或更改dates.jsondates.js.

如果你保存文件,因为.json你不必使用module.exports,你实际上不能,因为节点内置了对需要.json文件的支持。您甚至不必使用JSON.parse.