Skip to content
Advertisement

Unhandled Rejection: TypeError: Cannot read properties of undefined (reading ‘0’) getting error while trying to print JSON object in discord.js v14

I want to take the names from data.json and post it on a discord embed. For example I tried to print Animal Skull in a embed but it gave me that error.

error

Unhandled Rejection: TypeError: Cannot read properties of undefined (reading '0')

test.js

const { EmbedBuilder } = require("discord.js"); 
const datapath = ('data.json')

module.exports = {
  config: {
    name: "test",
    description: "Just a test command!",
  },
  permissions: ['SendMessages'],
  owner: false,
  run: async (client, message, args, prefix, config, db) => {

    message.reply({ embeds: [
      new EmbedBuilder()
        .setDescription(datapath.names[0])
        .setColor("Green")
    ] })
    
  },
};

my data.json

[
    {
        "names": "Animal Skull",
        "itemtype": "Block, 32, 4, No, Yes",
        "image": "https://static.wikia.nocookie.net/cubixworlds/images/4/4c/Animal_Skull.png/revision/latest?cb=20220720212850"
    },
    {
        "names": "Asteroid Block",
        "itemtype": "Block, 1, 1, No, Yes",
        "image": "https://static.wikia.nocookie.net/cubixworlds/images/f/fe/Asteroid_Block.png/revision/latest?cb=20220725063800"
    }
]

I would be really gratefull if anyone can help me.

Advertisement

Answer

You should use require to get data from json

const datapath = require('./data.json')

And your json contains an array of objects so use datapath[0].names to get Animal skull

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement