簡體   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