[英]Parse Nested json Array into Separate json Objects with Node.js
[英]Access nested json objects in node.js
我正在嘗試訪問嵌套的JSON
對象,但是卻Cannot read property 'module' of undefined
。
這是JSON
文件。
{
"server": {
"module": {
"InPluginPath": "/usr/home/nah/Website/server/httpModule.js"
}
}
}
然后,當我使用fs.readFile()
讀取文件后嘗試訪問JSON
對象時,出現Cannot read property 'module' of undefined
,錯誤。 下面是導致錯誤的行。
console.log(config.server.module.InPluginPath);
您需要JSON.parse()
從fs.readFile()
得到的字符串 。 例如:
fs.readFile('/tmp/foo.json', { encoding: 'utf8' }, function(err, data) {
if (err) throw err;
try {
data = JSON.parse(data);
} catch (ex) {
console.log('Error parsing json');
return;
}
console.log(data.server.module.InPluginPath);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.