Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a JSON object using a javascript variable

What I mean by that is say I have JSON data as such:

[{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}]

and I want to do something like this:

var x = "ADAM";
alert(data.x.TEST);
like image 442
Rudacles Avatar asked May 15 '11 18:05

Rudacles


People also ask

How do you access data in a JSON variable?

Answer: Use the JSON. parse() Method You can simply use the JSON. parse() method to parse a JSON string in JavaScript. The following example will show you how to convert a JSON string into a JS object and access individual values with pure JavaScript. It works in all major browsers.

How do I read a JSON file in JavaScript?

To fix this error, we need to add the file type of JSON to the import statement, and then we'll be able to read our JSON file in JavaScript: import data from './data. json' assert { type: 'JSON' }; console. log(data);

How do you find the value of an object in a variable?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!


1 Answers

var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
    x = "ADAM";

alert(data[0][x].TEST);

http://jsfiddle.net/n0nick/UWR9y/

like image 176
n0nick Avatar answered Oct 20 '22 04:10

n0nick