-1

In my object literals, I would like to create keys that would not be valid identifiers in order to generate a JSON file like the one in the picture, using JavaScript.

Is it possible to create the object like the following?

var objet = {
  targets: [
    new Stage(),
    {
      isStage: false,
      name: "Sprite1",
      blocks: {
        o7d.+f~]6/Bs|=|c/F(=: "Hello"
      }
    }
  ]
};

This is what the JSON file looks like:

JSON file

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Anas M K
  • 107
  • 1
  • 1
  • 7

3 Answers3

0

You can use the ES6 feature objet litteral dynamic key:

const illegalKey = 'o7d.+f~]6/Bs|=|c/F(=';
...
blocks: {
    [illegalKey]: "Hello"
}

Or just:

blocks: {
    'o7d.+f~]6/Bs|=|c/F(=': "Hello"
}
Faly
  • 13,291
  • 2
  • 19
  • 37
0

Yes, you can:

const data = {
  blocks: {
    "o7d.+f~]6/Bs|=|c/F(=": "Hello"
  }
}

console.log(data)

But please be careful what exactly you are doing, because you loose readability with this keys naming.

Jordan Enev
  • 16,904
  • 3
  • 42
  • 67
0

For understanding purpose, I have picked a sub-set of the object.

You can try following

var blocks = {
  "o7d.+f~]6/Bs|=|c/F(=": "Hello" // surround key with quotes
};

console.log(blocks["o7d.+f~]6/Bs|=|c/F(="]); // use bracket notation to fetch
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59