0

I have a problem accessing json keys with whitespaces or spacebars inside in pug for each loops. Backticks, single and double quotes didn't work for me so I had to fall back to this.

.pug file

for element in aJson
  for value, key in element
    if key == "my key with spaces"
      |  
      =value

Is there any other workaround that is cleaner or did I miss something? I use tabs for indentation in my .pug files. I'm using version 3.0.0 (https://www.npmjs.com/package/pug)

the following does not work:

.pug file

for element in aJson
  |  
  =element.`my key with spaces`
----> syntax error

for element in aJson
  |  
  =element.my key with spaces
-----> "my" not found error

my json file looks like this:

{
  "Element": [
    {
      "my key with spaces": "Value 1",
      "Key2": "Value 2",
      "Key3": "Value 3",
      "Key4": "Value 4",
      "Key5": "Value 5"
    },
  ],
  "Element2": [
    {
      "my key with spaces": "Value 1",
      "Key2": "Value 2",
      "Key3": "Value 3",
      "Key4": "Value 4",
      "Key5": "Value 5"
    },
  ],
  ...

}
  • Use bracket syntax to access the object key. See: [How can I access a JavaScript object which has spaces in the object's key?](https://stackoverflow.com/questions/8317982/how-can-i-access-a-javascript-object-which-has-spaces-in-the-objects-key) – Sean Feb 09 '21 at 17:12

1 Answers1

0

@Sean: Thank you that solves my issue. I was aware that you could use the index functions in pug using =element[0],=element[1],... but didn't know you could also access keys this way. Here is the code that worked for me

for element in aJson
  |  
  =element['my key with spaces']