Home > Enterprise >  Accessing JSON with a variable using square bracket notation not working in node.js Javascript
Accessing JSON with a variable using square bracket notation not working in node.js Javascript

Time:09-16

I'm using node.js. I read an object from a file as JSON using.

vc_channels.json file:

{
  "​hangout-room": "hangout-room is a voice and/or video room for anything sfw and not necessarily related to meditation."
}

code to read:

  fileContent = fs.readFileSync('./vc_channels.json');
  vc_channels = JSON.parse(fileContent);

but then when I try to access:

          console.log(vc_channels);
          console.log(channel.name);
          item.topic = vc_channels[channel.name];
          console.log(item.topic);

The result is undefined: console.log

{
  '​hangout-room': 'hangout-room is a voice and/or video room for anything sfw and not necessarily related to meditation.'
}
hangout-room
undefined

Does anyone know what I'm doing wrongly?

CodePudding user response:

If I copy your text for vc_channels.json, I can see that there is a \u200b (Zero width space) inside the "​hangout-room" part:

enter image description here

In the snipped bellow we can see that the first ASCII code is 200b and we have 68 afterwards which is h and so on:

const x = "​hangout-room";

// This prints: [200b","68", "61", "6e", "67", "6f", "75", "74", "2d", "72", "6f", "6f", "6d"]
console.log(x.split('').map(c => c.charCodeAt().toString(16)));

So you just have to remove the zero width space character from there. Just copy the output of this into your json file: "​hangout-room".replace('/200b', '') Or use any text editor which can show this kind of weird characters and lets you remove it.

  • Related