114

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.

A.L
  • 10,259
  • 10
  • 67
  • 98
Zar
  • 6,786
  • 8
  • 54
  • 76
  • 3
    The reason for this is that in JavaScript, as many other languages, a property's/variable's name cannot start with a number, but only with $, _, a-z and A-Z. Why isn't `Game.status[0]` an array? Then your syntax would be `Game.status[0][0]`. – nikc.org Jan 06 '12 at 13:50

7 Answers7

173

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"
        ]
    ]
}
fallerd
  • 1,512
  • 10
  • 15
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • This would still not allow you to do `Game.status[0].0` – JaredMcAteer Jan 06 '12 at 13:48
  • 19
    No, but will allow `Game.status[0][0]`. – Amadan Jan 06 '12 at 13:49
  • 5
    @OriginalSyn it's impossible to have ´Game.status[0].0´ because Javascript only allows property names to begin with a letter or an underscore if you want to use the dot notation. There's no way around that. – zatatatata Jan 06 '12 at 13:52
  • 1
    Thanks a lot for the answer, exactly what I was looking for. Honestly, I have no idea why I didn't think of an array to start with - I'll blame it on brain freeze. – Zar Jan 06 '12 at 13:56
  • @Quentin, `You aren't using JSON though. You have a JavaScript object literal.` Is the only difference the `var =` or are there more differences between JSON and an JS object literal? Is a JS object basically JSON stored in a variable? – Andre Bulatov Oct 04 '15 at 04:03
  • @AndreBulatov — JSON is a data format like CSV or XML. A JavaScript object literal is part of a JavaScript program. JSON syntax is inspired by JavaScript literal syntax but is significantly simpler. – Quentin Oct 04 '15 at 19:58
  • So if I create a small ~500 line database of definitions for some items in JSON format like this http://jsoneditoronline.org/, then the second I put it inside JavaScript code, we call it an object literal? If so, is it because only way to include it is in a `var` and only way for JS engine to read a var in "JS(ON)" format is as an object (and also because JSON is just a spawn of the neatness of JS objects' syntax)? – Andre Bulatov Oct 05 '15 at 06:00
  • Or an array literal, or whatever the data type you use is. It isn't the only way to include it: You could store it in a separate file (in which case it would actually be JSON) and then read it in and parse it (using the `JSON.parse()` function) – Quentin Oct 05 '15 at 08:12
  • For reference, [RFC4627](https://tools.ietf.org/html/rfc4627) makes clear: > An object is an unordered collection of zero or more name/value pairs, where a **name is a string** and a value is a string, number, boolean, null, object, or array. *(emphasis mine)* – Adam Batkin Dec 04 '17 at 15:05
9

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.

Andreas
  • 5,393
  • 9
  • 44
  • 53
Amadan
  • 191,408
  • 23
  • 240
  • 301
6

Probably you need an array?

var Game = {

    status: [
        ["val", "val","val"],
        ["val", "val", "val"]
    ]
}

alert(Game.status[0][0]);
yatskevich
  • 2,085
  • 16
  • 25
3

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?

zatatatata
  • 4,761
  • 1
  • 20
  • 41
2

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.

Huiguorou
  • 317
  • 2
  • 4
1

JSON is "JavaScript Object Notation". JavaScript specifies its keys must be strings or symbols.

The following quotation from MDN Docs uses the terms "key/property" to refer to what I more often hear termed as "key/value".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

2540625
  • 11,022
  • 8
  • 52
  • 58
0

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.

Willem Mulder
  • 12,974
  • 3
  • 37
  • 62
  • "JSON is the 'string' version of a Javascript Object." That is not true. A JSON object is a subset of a JavaScript Object. Otherwise you're correct that is a JavaScript Object since it doesn't conform to the JSON spec – JaredMcAteer Jan 06 '12 at 13:47
  • JSON is a subset of JavaScript *object literal notation* and a JSON object is a data type that can be expressed in JSON. – Quentin Jan 06 '12 at 13:51
  • @OriginalSyn: Well, not really. JSON is an "interchangeable" format, and is used as a language-independent string format. Most languages can parse JSON, and in Javascript, it will turn into a Javascript Object. See http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/. – Willem Mulder Jan 06 '12 at 13:59
  • 2
    @OriginalSyn: In JavaScript, object literals are _never_ JSON, because JSON is _always_ a string. Object literals are not strings. The term "JSON object" doesn't make sense, because something can't be both "JSON" - a string, and an "object" - a non-string. – nnnnnn Jan 06 '12 at 14:59