Reputation: 107
I'm fetching JSON data via jQuery's get function:
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
$.each(data, function (index, item) {
var ticker = {
id: [item.id],
name: [item.name],
symbol: [item.symbol],
rank: [item.rank],
price_usd: [item.price_usd],
price_btc: [item.price_btc],
24h_volume_usd: [item.24h_volume_usd],
market_cap_usd: [item.market_cap_usd],
available_supply: [item.available_supply],
percent_change_1h: [item.percent_change_1h],
percent_change_24h: [item.percent_change_24h],
percent_change_7d: [item.percent_change_7d],
last_updated: [item.last_updated]
};
});
});
As an example, the item variable itself (console.log) contains this kind of data:
{
id: "bitcoin",
name: "Bitcoin",
symbol: "BTC",
rank: "1",
price_usd: "2238.86",
price_btc: "1.0",
24h_volume_usd: "1206490000.0"
// ...
}
However, when I try to access item.24h_volume_usd
, the javascript throws following error:
SyntaxError: identifier starts immediately after numeric literal
I read afterwards that javascript cannot have variables that start with numbers. So the question is:
How do i access this variable then?
Upvotes: 0
Views: 69
Reputation: 133403
Use Bracket notation i.e item["24h_volume_usd"]
to read and while defining property wrap it in quotes as (property name starts with a number)
var data = {
"24h_volume_usd": "1206490000.0"
}
console.log(data["24h_volume_usd"])
However, I would recommend you to use valid Identifiers.
Upvotes: 2