问题
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.
回答1:
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[0][0].
But given that data, an array would seem to make more sense.
var Game={
"status": [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
]
}
回答2:
Probably you need an array?
var Game = {
status: [
["val", "val","val"],
["val", "val", "val"]
]
}
alert(Game.status[0][0]);
回答3:
First off, it's not JSON: JSON mandates 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 numbers with the dot notation (.0).
Alternatively, you can quote the numbers (i.e. { "0": "val" }...); you will have plain objects instead of Arrays, but the same syntax will work.
回答4:
When a Javascript object property's name doesn't begin with either an underscore or a letter, you cant use the dot notation (like Game.status[0].0), and you must use the alternative notation, which is Game.status[0][0].
One different note, do you really need it to be an object inside the status array? If you're using the object like an array, why not use a real array instead?
回答5:
JSON regulates key type to be string. The purpose is to support the dot notation to access the members of the object.
For example, person = {"height":170, "weight":60, "age":32}. You can access members by person.height, person.weight, etc. If JSON supports value keys, then it would look like person.0, person.1, person.2.
回答6:
What about
Game.status[0][0] or Game.status[0]["0"] ?
Does one of these work?
PS: What you have in your question is a Javascript Object, not JSON. JSON is the 'string' version of a Javascript Object.
来源:https://stackoverflow.com/questions/8758715/using-number-as-index-json