How would i add a key:value pair to a json list in node.js?

Viewed 79

I am using node.js, and i want to add the arguments from a command and the server id as a key:value pair into a json file like this:

{

    "guildid": "args",
    "guildid2": "args2",

}

And the current code that i have is far from what i want, where this code:

const command = args.shift().toLowerCase();
const args = message.content.slice(config.prefix.length).trim().split(' ');

if (command === 'setup') {
const guildid = message.guild.id
        const data = { 
            [guildid]: `${args}`
            }
        const groupname = JSON.stringify(data, null, 2);
        fs.writeFile('./groups.json', groupname,{flags: "a"}, finished);
        function finished(err) {
            message.channel.send(`Success! Your group, **${args}**, has been registered to **${message.guild.name}**`
            )}

Outputs what i want to the json file, but if i run the command again it just appends to the end:

{
  "guildid": "args"
}{
  "guildid2": "args2"
}

I understand now that using the a flag just appends to the end no matter what and const data is what is giving it the brackets, but i want to know how to be able to format it in the way i showed at the beginning. Apologies for any glaring errors i have made, this is one of my first times using javascript and node.js.

1 Answers

You'll have to get the original file first using fs.readFile[Sync] and JSON.parse, and then add on the property as you would any other object:

obj.key = 'value';

// or in your case:
obj[key_variable] = 'value';

You should also omit the 'a' flag as it will append another object (resulting in a syntax error) instead of modifying the one already there. Your code should look like this:

const guildid = message.guild.id;
const data = JSON.parse(fs.readFileSync('/groups.json'));

/* 
  You could either use:
  data[guildid] = `${args}`;

  OR, when stringifying to the file:
  const groupname = JSON.stringify({ 
    ...data, 
    [guildid]: `${args}` 
  }, null, 2);

  Either way will work
*/ 

data[guildid] = `${args}`;
const groupname = JSON.stringify(data, null, 2);

// remove { flags: 'a' }
fs.writeFile('./groups.json', groupname, finished);

// you should probably write some error handling
function finished(err) {
 message.channel.send(
  `Success! Your group, **${args}**, has been registered to **${message.guild.name}**`
 );
}
Related