1

I need to use a variable when selecting data from a json source like this. The json is retrieved with jquery getJSON().

"prices":[{
    "fanta":10,
    "sprite":20,
}]

var beverage = fanta;
var beverage_price = data.prices.beverage;

Now beverage_price = 10

var beverage = sprite;
var beverage_price = data.prices.beverage;

Now beverage_price = 20

When I try to do it like in the examples, the script tries to look up the beverage entry in prices.

Thanks a lot!!

VisioN
  • 143,310
  • 32
  • 282
  • 281
Nesvik
  • 13
  • 3
  • 2
    Use square bracket notation `data.prices[beverage]`. – Matt Mar 15 '13 at 12:36
  • 3
    ... `data.prices` is an array: `[0]` is required. – VisioN Mar 15 '13 at 12:36
  • possible duplicate of [How to use variables in dot notation like square bracket notation](http://stackoverflow.com/questions/7102704/how-to-use-variables-in-dot-notation-like-square-bracket-notation) – Matt Mar 15 '13 at 12:37

2 Answers2

2

You can access it like:

var beverage = 'fanta';
var beverage_price = data.prices[0][beverage];
techfoobar
  • 65,616
  • 14
  • 114
  • 135
0

As VisioN mentioned in the comment, data.prices is an array, you need to access its first element with [0] which contains prices { "fanta":10, "sprite":20}

here is the working example : http://jsfiddle.net/2E8AH/

Or else you can make data.prices an object like below : (if it is in your control)

var data = {
    "prices" : 
        {
            "fanta":10,
            "sprite":20,
        }
};

and can access without [0] like this : http://jsfiddle.net/Y8KtT/1/

Community
  • 1
  • 1
Anil Bharadia
  • 2,760
  • 6
  • 34
  • 46