-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
  • 16,564
  • 7
  • 51
  • 69
Anas M K
  • 97
  • 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
  • 12,802
  • 1
  • 18
  • 35
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
  • 14,524
  • 3
  • 39
  • 62
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
  • 27,657
  • 4
  • 40
  • 56