0

I am trying to pull data from a online API in JSON format as abstractly as possible.

I have code in the exact same structure as this:

require("request")

var url = ""//Myurl

request({
url: url,
json: true
}, function (error, response, body) {

if (!error && response.statusCode === 200) {
    console.log(body) 
}
})

And I have a JSON like this:

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

I want to refer to "John" using this way

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

instead of going this way

      console.log(body.John.ID);

to access his ID.

I have tried using for each on the body response to get the name and then access it through that, but I couldn't get that right.

Djinnes
  • 17
  • 1
  • 7

1 Answers1

1

Do this:

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

This will point your body object to value of the variable tempName instead of the name of the variable.

dimitrisk
  • 774
  • 9
  • 15