views:

183

answers:

2
+1  Q: 

JSON numeric key

I have a JSON object like:

var myObject = { '0' : 'blue' };

Now, in JavaScript, when I try to access the value of the key '0' like:

myObject.0 

...I am getting an error. (Maybe this is not the proper way?)

How can I access the value of a key that is a number (like the above)?

+9  A: 

This should work:

myObject["0"]

(myObject["propertyName"] is an alternative syntax for myObject.propertyName.)

You're getting the error because, in JavaScript, identifiers can't begin with a numeral. From the Variables page at the Mozilla Developer Centre:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Steve Harrison
Properties *can* begin with a number. It's just that the "." syntax allows only identifers after the dot.
Alsciende
Thanks for answer. It worked.
Prashant
@Alsciende: Ah, thanks! I've corrected the relevant information in my answer.
Steve Harrison
+2  A: 

myObject["0"]

Amarghosh
Thanks for answer.
Prashant