node.js - 如何在nodejs中读取json文件?
问题描述
我的应用程序中有一个配置 json 文件。
{
"Name":{
"Catgory":{
"Val":{
"Gaby": "122"
},
"Batch":{
"Hede" : "86"
}
}
}
}
我有很多像上面这样的配置。但是当我尝试像下面那样阅读时,我做不到。
I have imported the file as config in the current file. When I try to read as below I'm able to get the values.
config.Name.Catgory.Val
但是代替 Val,如果我尝试动态获取值,例如
configVal = "Val"
And if I try to call,
config.Name.Catgory.configVal I'm unable to read. Can anyone please help me with this?
解决方案
您需要使用括号符号来动态访问值:
const config = {
"Name":{
"Catgory":{
"Val":{
"Gaby": "122"
},
"Batch":{
"Hede" : "86"
}
}
}
}
let configVal = 'Val';
console.log(config.Name.Catgory[configVal]);
推荐阅读
- python - 上课点 - Python
- sql - SQLite 日期调整不正确
- mongodb - 使用 ReactiveMongo 库表示要存储在 mongo 中的产品
- reactjs - 如何知道所有表单数据在 react-hook-form 库中验证
- javascript - 切换到功能组件的问题与 useEffect 反应
- sql - 如何在 SQL 中的不同列中显示计数
- vue.js - 我的头文件应该从 Nuxt 中的“store”文件夹而不是“components”文件夹中调用吗?
- reactjs - 用户单击链接并被重定向后,如何使功能自动激活
- r - 如何应用 actionButton 来更新我在 R 中的 Shiny?
- javascript - 使用 .then() 嵌套异步函数