无法获得JSON密钥的值,只返回密钥

时间:2018-03-29 16:55:16

标签: javascript json node.js express

在过去的几个月里,我在Google Go上做了大量的工作后,我又回到了Express堆栈。我正在为工作构建简单的webapp页面,迭代JSON对象。我试图在作为较大对象一部分的对象中打印每个键的值,但只记录了该键?

这是我读过的data.json(在整个对象中只显示了一个对象并省略了安全数据。):

{
    "Prod18r2" : {
        "baseAPIURL" : "https://apiurl.com/",
        "serviceEndpoints" : {
            "restaurantManager" : "https://prodapiurl.com/rm/",
            "transactionManager" : "https://prodapiurl.com/rm/",
            "userManager" : "https://prodapiurl.com/rm/",
            "recordHistory" : "https://prodapiurl.com/rm/"
        }
    }
}

这是我的tryrate.js文件中的迭代和日志逻辑:

for(var x in INSTANCES.Prod18r2.serviceEndpoints) {
    console.log(x);
}

输出:

  

PS   C:\ Users \用户payton.juneau \桌面\我\项目\节点\ ETM-占卜-web应用>节点   。\ test.js restaurantManager transactionManager userManager   recordHistory PS   C:\ Users \用户payton.juneau \桌面\我\项目\节点\ ETM-占卜-web应用>

预先感谢任何回复,我知道这可能是令人尴尬的愚蠢。

2 个答案:

答案 0 :(得分:2)

需要object[keyName]才能获得值



var INSTANCES = {
  "Prod18r2": {
    "baseAPIURL": "https://apiurl.com/",
    "serviceEndpoints": {
      "restaurantManager": "https://prodapiurl.com/rm/",
      "transactionManager": "https://prodapiurl.com/rm/",
      "userManager": "https://prodapiurl.com/rm/",
      "recordHistory": "https://prodapiurl.com/rm/"
    }
  }
}
//Here is my iterate-and-log logic right now in a test.js file:

for (var x in INSTANCES.Prod18r2.serviceEndpoints) {
  console.log(INSTANCES.Prod18r2.serviceEndpoints[x]);
}




答案 1 :(得分:0)

你应该

for(var serviceEndpoints in INSTANCES.Prod18r2.serviceEndpoints) {
    console.log(INSTANCES.Prod18r2.serviceEndpoints[serviceEndpoints]);
}

我替换你的" x" for" serviceEndpoints"并使用返回的密钥获取json值。