Varun Jain
Varun Jain

Reputation: 903

JavaScript Issue using JSON Object

I'm pulling a JSON object via Meteor, and I'm retrieving it correctly

https://api.bitcoinaverage.com/ticker/USD

{
  "24h_avg": 147.77,
  "ask": 144.85,
  "bid": 144.33,
  "last": 144.81,
  "timestamp": "Thu, 17 Oct 2013 02:30:18 -0000",
  "total_vol": 79387.48
}

When I try to use the values, I get the following results

obj.ask
144.96
obj.24h_avg
SyntaxError: Unexpected token ILLEGAL
obj.total_vol
79773.46

Why am I getting an issue with the 24h_avg? I'm pretty darn lost here!

Thanks in advance!

Upvotes: 0

Views: 50

Answers (2)

PSL
PSL

Reputation: 123739

You need to use [] notation on the object to access the values with the key having invalid characters for a key (Here they start with digits, same applies to other chars like - etc in the key).

So try

 obj["24h_avg"]


 obj.24h_avg // You are accessing a property it needs to be a valid identifier.

 obj["24h_avg"] // You are accessing a property value using ["property_name"] it need not  be a valid identifier.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

keys cannot start with digits, so need to use the bracket notation to access the member

so use

obj['24h_avg']

Upvotes: 1

Related Questions