Use variable as key to parse json [duplicate]
I have a var, let's say
var product = "something"
I have a json file that looks like
{
"something": [
{
"price": "2000"
}
],
....
I need to access "price" from "something", so I'm trying
data.product.price
and it gives me undefined. I can easily get price value using data.something.price , but in my case it won't work because var product is dinamic value, so I need help with parsing my json, using my var as a key.
Solution 1:
You will have to use square brackets here, and also, your price
is inside an array so you need to access it using [0]
data[product][0].price
Here, I select something
object using data[product]
and later, to select the first object in the array, I used [0]
and then I select price
key.
var product = 'something';
$.get('https://api.jsonbin.io/v3/b/596b31ce194a6c7f2b90406e', function(data) {
console.log(data[product][0].price);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>