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!!

3
  • 2
    Use square bracket notation data.prices[beverage]. Commented Mar 15, 2013 at 12:36
  • 3
    ... data.prices is an array: [0] is required. Commented Mar 15, 2013 at 12:36
  • possible duplicate of How to use variables in dot notation like square bracket notation Commented Mar 15, 2013 at 12:37

2 Answers 2

3

You can access it like:

var beverage = 'fanta';
var beverage_price = data.prices[0][beverage];
Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.