Using a Number as an "Index" (JSON)

I recently started digging into JSON, and I'm currently trying to use the number as an "identifier", which doesn't work too well. foo:"bar" working fine, but 0:"bar" is not.

 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 this as follows? Something like Game.status[0].0 Would make my life easier. Of course, there are other ways, but this way is preferred.

+44
json javascript identifier
Jan 06 2018-12-12T00:
source share
5 answers

JSON only resolves key names. These lines may consist of numerical values.

However, you are not using JSON. You have a JavaScript object literal. You can use identifiers for keys, but an identifier cannot begin with a number. However, you can still use strings.

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

If you access properties with dotted notation, you need to use identifiers. Instead, use the square notation: Game[0][0] .

But given this data, the array seems to make more sense.

 var Game={ "status": [ [ "val", "val", "val" ], [ "val", "val", "val" ] ] } 
+69
Jan 6 2018-12-12T00:
source share

Maybe you need an array?

 var Game = { status: [ ["val", "val","val"], ["val", "val", "val"] ] } alert(Game.status[0][0]); 
+4
Jan 06 2018-12-12T00:
source share

Firstly, this is not JSON: JSON ensures that all keys must be strings.

Secondly, regular arrays do what you want:

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

will work if you use Game.status[0][0] . You cannot use dot notation numbers ( .0 ).

Alternatively, you can specify numbers (ie { "0": "val" }... ); you will have simple objects instead of arrays, but the same syntax will work.

+3
Jan 6 2018-12-12T00:
source share

If the property name of the Javascript object does not start with either an underscore or a letter, you cannot use dot notation (for example, Game.status[0].0 ), but you must use alternative notations that Game.status[0][0] .

One note, do you really need it to be an object inside a state array? If you use an object as an array, why not use a real array?

+3
Jan 06 '12 at 13:50
source share

What about

 Game.status[0][0] or Game.status[0]["0"] ? 

Does one of them work?

PS: You have a Javascript object in your question, not JSON. JSON is a "string" version of a Javascript object.

0
Jan 06 2018-12-12T00:
source share



All Articles