首页 > 解决方案 > 如何在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?

标签: node.jsjson

解决方案


您需要使用括号符号来动态访问值:

const config = {
 "Name":{
     "Catgory":{
        "Val":{
           "Gaby": "122"
         },
        "Batch":{
            "Hede" : "86"
         }
       }
    }
 }
 
 let configVal = 'Val';
 console.log(config.Name.Catgory[configVal]);


推荐阅读