-3

I am trying to make a command command that allows the author to set up a command for their server, This is meant to update a json file not overwrite it, I am using node.js and discord.js

const fs = require('fs')
module.exports = {
    name: 'setsuggest',
    execute(client, message, args, discord, cmd){
        const channelid = args[0]
        const serverid = message.guild.id
        
    
        fs.readFile('suggest.json', function (err, JsonData) {
            var json = JSON.parse(JsonData)
            let data = { 
                [serverid]: channelid 
            };
            json.push(data)
            fs.writeFile('suggest.json', JSON.stringify(json), function (err) {
                if (err) throw err;
                console.log('Updated')
            })
        })
        
    }
}

What am I doing wrong?

St34lthr
  • 1
  • 2
  • 4
    I suspect json is an object not an array. https://stackoverflow.com/questions/8925820/javascript-object-push-function – Matt Jun 30 '21 at 20:03

1 Answers1

1

If json is an object, as it seems from your usage, you could use the spread operator to populate a new object with all properties from the parsed object and the add the property from serverid to it:

var json = {...JSON.parse(JsonData), [serverid]: channelid};

Otherwise you can always just assign the property in the parsed object directly:

var json = JSON.parse(JsonData);
json[serverid] = channelid;
Flygenring
  • 3,818
  • 1
  • 32
  • 39