34

I have an object like:

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

Now, 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)?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Prashant
  • 5,331
  • 10
  • 44
  • 59
  • 7
    By the way, that isn't a JSON object—it's a *JavaScript* object. JSON is simply a data storage format that's based on JavaScript syntax. – Steve Harrison Jan 08 '10 at 10:27

3 Answers3

73

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
  • 121,227
  • 16
  • 87
  • 72
8

myObject["0"]

Amarghosh
  • 58,710
  • 11
  • 92
  • 121
1

if you have data like

  `"rain": {
           "3h": 0
         },` 

then you can simply access it rain['3h']

paicubes
  • 151
  • 1
  • 7