'Getting data from json says undefined in discord.js

Heyo, I want to get a data from a json file but it says undefined. This is my json file:

[
  {
    "channel": [
      "960229917264584736"
    ],
    "info": {
      "cooldown": 3000
    }
  },
  {
    "channel": [
      "960229880405053473"
    ],
    "info": {
      "cooldown": 6000
    }
  }
]

And here is how i'm trying to get it:

let channels = JSON.parse(fs.readFileSync("./channels.json")); 
    console.log(channels.channel)

Thanks for helping^^



Solution 1:[1]

The error in the code comes down to the wrong mapping in JavaScript.

Note that in JavaScript code, channels corresponds to a JSON array with multiple channels, like this:

let channels = [{channel1}, {channel2}] // the file JSON is an array [{},{}]

So to access a channel you will need to go to the following path:

channels[0].channel // 0 can be replaced for any valid index number
// output: {"channel": ["960229917264584736"],"info": {"cooldown": 3000}}

To get a channel id:

channels[0].channel[0]
// output: "960229917264584736"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yeshayahu