Balizok
Balizok

Reputation: 1038

How to access json file data from js file

I'm developing a discord bot and i wanted to send a random sentence from my dactylo.json file when the user sends a specific message. However, when trying to access data from this file, I get an "undefined" error like it couldn't read my json file. I looked over many previous questions but couldn't find an answer that helped me, even though it helped other people. I'm sure I'm missing something but I can't seem to find what...

Here's my code from dactylo.json :

{
    "sentences":[
        {
            "sentence": "Un dragon gradé dégrade un gradé dragon.",
            "top":"0",
            "player":"Personne"
        },
        {
            "sentence":"Le mur murant Paris rend Paris murmurant.",
            "top":"0",
            "player":"Personne"
        },
        {
            "sentence":"Le cricri de la crique crie son cri cru et critique car il craint que l'escroc ne le croque et ne le craque.",
            "top":"0",
            "player":"Personne"
        }
    ]
}

And my code from dactylo.js where I try to get data :

const fs = require('fs');

module.exports = {
    name: 'dactylo',
    description: 'Démarre une partie de dactylo',
    execute(message) {
        message.reply("Recopiez la phrase suivante le plus rapidement possible :")
        const data = fs.readFileSync('C:/Users/steph/Documents/Discord Bot/commands/fun/dactylo.json');

        const sentences = data.sentences;
        var sentence = sentences[Math.floor(Math.random() * sentences.length)];
        message.channel.send(sentence);
    },
};

And the error I get in case it helps :

TypeError: Cannot read property 'length' of undefined
    at Object.execute (C:\Users\steph\Documents\Discord Bot\commands\fun\dactylo.js:11:71)
    at Client.<anonymous> (C:\Users\steph\Documents\Discord Bot\main.js:42:11)
    at Client.emit (events.js:375:28)
    at MessageCreateAction.handle (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\steph\Documents\Discord Bot\node_modules\ws\lib\event-target.js:132:16)
    at WebSocket.emit (events.js:375:28)

Upvotes: 0

Views: 161

Answers (3)

hp10
hp10

Reputation: 632

You can simply import json file on the beginning:

const dactylo = require('<path_to_json>.json');

Upvotes: 1

Marcello Del Buono
Marcello Del Buono

Reputation: 176

In your case, the fs.readFileSync function returns a Buffer, not the parsed json content as you expect.

In order to obtain the parsed JSON content, you need to follow two steps:

  1. Read the .json file content as text
  2. Parse the text with JSON.parse

The following code illustrates how it works:

const jsonPath = 'C:/Users/steph/Documents/Discord Bot/commands/fun/dactylo.json';
const jsonText = fs.readFileSync(jsonPath, "utf8"); 
const jsonObject = JSON.parse(jsonText);
console.log(jsonObject.sentences.length);   // 3

Notice that the second parameter passed to the fs.readFileSync function tells the function to return the file content as String and not as Buffer.

Upvotes: 0

mikach
mikach

Reputation: 2427

You can use require to automatically parse JSON for you

const data = require('path/to/file.json');

Also, it's better practice to use a relative path to the file instead of an absolute.

Upvotes: 0

Related Questions