[javascript] 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.

This question is related to javascript json identifier

The answer is


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.


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.


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.


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?


Probably you need an array?

var Game = {

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

alert(Game.status[0][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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to identifier

Are PostgreSQL column names case-sensitive? getting the error: expected identifier or ‘(’ before ‘{’ token How to call on a function found on another file? Hibernate error: ids for this class must be manually assigned before calling save(): PostgreSQL Error: Relation already exists Using number as "index" (JSON) How does jQuery work when there are multiple elements with the same ID value? Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView What is the meaning of single and double underscore before an object name?