rohit1248
rohit1248

Reputation: 181

How to print JSON values in javascript fetched using AJAX

I have made a js file in which data is being fetched from js file and the values are stored in a request object. Example of JSON file

{
    "name": "ABC",
    "age": 20
}

I want to display the value of name using variable name. I want something like this.

var x = "name";
var req = JSON.parse(request.responseText);
console.log(req.x);

But the above statement displays undefined. Any solutions?

Upvotes: 1

Views: 70

Answers (4)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

Use brackets instead of dot:

var x = "name";
var req = {
  "name": "ABC",
  "age": 20
};

console.log(req[x]);

You need to use brackets here because the name of the property is dynamic, with the value coming from a variable (dot should be used only when the name of the property is static)

Upvotes: 4

Ziya ERKOC
Ziya ERKOC

Reputation: 839

You can also use console.log(req.name)

Upvotes: 0

qiAlex
qiAlex

Reputation: 4346

Use obj[key]

console.log(req[x]);

Upvotes: 1

Nishit Kothari
Nishit Kothari

Reputation: 39

It should be console.log(req[x]);

OR

console.log(req.name);

Upvotes: 1

Related Questions