Using number as "index" (JSON)

Zar picture Zar · Jan 6, 2012 · Viewed 108.5k times · Source

Recently started digging in to JSON, and I'm currently trying to use a number as "identifier", which doesn't work out too well. foo:"bar" works fine, while 0:"bar" doesn't.

var Game = {
    status: [
                {
                    0:"val",
                    1:"val",
                    2:"val"
                },
                {
                    0:"val",
                    1:"val",
                    2:"val"
                }
           ]
}

alert(Game.status[0].0);

Is there any way to do it the following way? Something like Game.status[0].0 Would make my life way easier. Of course there's other ways around it, but this way is preferred.

Answer

Quentin picture Quentin · Jan 6, 2012

JSON only allows key names to be strings. Those strings can consist of numerical values.

You aren't using JSON though. You have a JavaScript object literal. You can use identifiers for keys, but an identifier can't start with a number. You can still use strings though.

var Game={
    "status": [
        {
            "0": "val",
            "1": "val",
            "2": "val"
        },
        {
            "0": "val",
            "1": "val",
            "2": "val"
        }
    ]
}

If you access the properties with dot-notation, then you have to use identifiers. Use square bracket notation instead: Game.status[0][0].

But given that data, an array would seem to make more sense.

var Game={
    "status": [
        [
            "val",
            "val",
            "val"
        ],
        [
            "val",
            "val",
            "val"
        ]
    ]
}