user13992262
user13992262

Reputation:

Need help getting JSON.parse() to work (Discord Bot)

I have a seperate JSON file which is linked as

const Players = require('./Database/Players.json');

and a praser that goes through the code

client.on('message', message => {


    if (message.content.toLowerCase() ==='smack activate') {
        
        let PlayerData = [message.author.username];

        Activate [message.author.username] = {
        AccountActive: 1,
        Health: 100,
        Level: 1,
        Lust: 0,
        Items: ""
        };

        var parsedata = JSON.parse(Players)   // <-----------
        if (parsedata.PlayerData.accountactive === 1) {
            message.channel.send ("Account Already Activated");
            return;
        }

        fs.writeFile("./Database/Players.json", JSON.stringify (Activate, null, 4), err => {
            if (err) throw err;
            message.channel.send ("Account Activated")
        });
    };

But nothing seems to work.. what am I doing wrong? I'm getting this error message

undefined:1
[object Object]
 ^

Upvotes: 0

Views: 285

Answers (2)

antonku
antonku

Reputation: 7665

As far as I understand you are trying to do the following:

  1. Check if the message author is a known player with an activated account.
  2. If yes - send the message that the account is already activated and return.
  3. Otherwise - add the new player data to the known players.

You probably can do this in this following way:

const Players = require('./Database/Players.json');

client.on('message', message => {
  if (message.content.toLowerCase() === 'smack activate') {

    const PlayerData = Players[message.author.username];

    if (PlayerData && (PlayerData.AccountActive === 1)) {
      message.channel.send("Account Already Activated");
      return;
    }

    Players[message.author.username] = {
      AccountActive: 1,
      Health: 100,
      Level: 1,
      Lust: 0,
      Items: ""
    };

    fs.writeFile("./Database/Players.json", JSON.stringify(Players, null, 4), err => {
      if (err) throw err;
      message.channel.send("Account Activated")
    });
  };

})

Upvotes: 0

antonku
antonku

Reputation: 7665

Take a look at how require works. As described in the documentation: https://nodejs.org/api/modules.html#modules_all_together

LOAD_AS_FILE(X)

  1. If X is a file, load X as its file extension format. STOP
  2. If X.js is a file, load X.js as JavaScript text. STOP
  3. If X.json is a file, parse X.json to a JavaScript Object. STOP
  4. If X.node is a file, load X.node as binary addon. STOP

So you should not call JSON.parse, because require automatically parses json modules into JavaScript objects.

Upvotes: 1

Related Questions