使用数字作为“索引” (JSON) [英] Using number as "index" (JSON)

查看:112
本文介绍了使用数字作为“索引” (JSON)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近开始深入研究JSON,我目前正在尝试使用一个数字作为标识符,这不是很好。 foo:bar工作正常,而 0:bar没有。

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);

有没有办法按以下方式进行?类似 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.

推荐答案

JSON只允许键名作为字符串。这些字符串可以包含数值。

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

您不使用JSON。你有一个JavaScript对象文字。您可以使用密钥标识符,但标识符不能以数字开头。你仍然可以使用字符串。

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"
        }
    ]
}

如果使用点符号访问属性,则必须使用标识符。使用方括号表示法: Game [0] [0]

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"
        ]
    ]
}

这篇关于使用数字作为“索引” (JSON)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆