【发布时间】:2018-10-20 12:20:57
【问题描述】:
我在尝试从 JSON 文件解析空(字符串化)数组时遇到问题,我得到的是字符串,而不是返回空数组。
我的 JSON 文件初始设置是:
"[]"
我正在使用文件系统将解析的数据分配给一个变量
let parsedObjs = JSON.parse(fs.readFileSync(__dirname + '/data/employees.json'));
当我在浏览器控制台中尝试这个时,我得到了一个空数组,正如我所期望的:
JSON.parse("[]")
> []
但是,在 Node/Express 中,我得到了一个返回的字符串:
console.log(type of:', typeof parsedObjs);
> type of: string
奇怪的是,如果我将初始文件设置为未字符串化的数组,它会返回一个数组:
> []
当然,这会产生“JSON 意外结束”错误。
我对此很陌生,请告诉我我做错了什么。谢谢。
额外信息
完整的功能:
function populateSelectors(selector) {
let foundOptions = [];
let parsedObjs = JSON.parse(fs.readFileSync('./data/employees.json'));
parsedObjs.forEach(obj => {
let key = Object.keys(obj)[0];
let optionName = obj[key][selector];
if (foundOptions.indexOf(optionName) === -1 ) {
foundOptions.push(optionName);
}
});
return foundOptions;
}
完全错误(我显然已将完整路径更改为):
SyntaxError: Unexpected end of JSON input
application.js:630
at JSON.parse (<anonymous>)
at Object.populateSelectors (<FULL PATH>\Rota Application 2\staff.js:14:27)
at <FULL PATH>\Rota Application 2\app.js:45:28
at Layer.handle [as handle_request] (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\layer.js:95:5)
at next (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\layer.js:95:5)
at <FULL PATH>\Rota Application 2\node_modules\express\lib\router\index.js:281:22
已解决!
问题是我在别处有一个 writeFile 方法,他们都试图同时访问该文件。我把它改成 writeFileSync 问题解决了!
【问题讨论】:
标签: javascript arrays json node.js express