Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using number as "index" (JSON)

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.

like image 889
Zar Avatar asked Jan 06 '12 13:01

Zar


People also ask

Can I use number in JSON key?

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

Can you index a JSON object?

You can index JSON data as you would any data of the type that you use to store it. In particular, you can use a B-tree index or a bitmap index for SQL/JSON function json_value , and you can use a bitmap index for SQL/JSON conditions is json , is not json , and json_exists .

Can JSON include numbers?

It can be either. Both strings and numbers are valid JSON values.

Can JSON properties start with a number?

Illegal meaning that with dot notation, you're limited to using property names that are alphanumeric (plus the underscore _ and dollar sign $ ), and don't begin with a number.


1 Answers

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"         ]     ] } 
like image 159
Quentin Avatar answered Sep 18 '22 15:09

Quentin