繁体   English   中英

访问node.js中的嵌套json对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM