用变量值而不是文字遍历JSON树,使用NodeJS不起作用

Traversing JSON tree with variable value instead of literal not working using NodeJS

本文关键字:使用 NodeJS 不起作用 JSON 遍历 变量值 文字      更新时间:2023-09-26

我正试图从JSON格式的在线API中提取数据,尽可能抽象。

我有一个完全相同结构的代码:

require("request")
var url = ""//Myurl
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
    console.log(body) 
}
})

JSON是这样的:

    { John:
       { ID: 1212,
         Age: 12
       }
    }

我想这样称呼"John"

      var tempName = "John";//not limited to it being in the same scope
      console.log(body.tempName.ID);

而不是这样

      console.log(body.John.ID);

访问他的ID。

我试过在body response上使用for each来获取名称,然后通过它访问它,但我不能得到正确的。

这样做:

console.log(body[tempName].ID);

这将把你的body对象指向变量tempName的值,而不是变量的名称。