JS / Jquery - using variable in json selector
I need to use a variable when fetching data from a json source like this. Json is retrieved using 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 find a record of drinks in prices.
Thank you so much!
source to share
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 a working example: http://jsfiddle.net/2E8AH/
Or you can make the data.prices
object like below: (if under your control)
var data = {
"prices" :
{
"fanta":10,
"sprite":20,
}
};
and can be accessed without [0]
like this: http://jsfiddle.net/Y8KtT/1/
source to share