Syntaxis
Syntaxis

Reputation: 21

How do I edit a singular value in a JSON file with Node.JS/Javascript

I'm making a discord bot with discord.js and I have a system that I have the ability to turn off and on by changing a value in a JSON file from true to false and vice versa. I created a command that allows moderators in discord to turn that system on and off. This is where my question comes in. In that JSON file, I have 2 values.

One is an array that holds different strings with which the system will randomly pick to send a message back into the discord

and the 2nd value is just a boolean called timedStatus and it's set to either true or false to turn the system on and off. I was wondering how I can change JUST that value without affecting the array. I've done something similar to this before but I just can not remember how to do it.

This is my code for the command.

if (cmd === prefix + "timedreplies") {
        if (timedReplies.replystatus = true) {
            console.log("Timed replies set to off");
            // Set to off
        } else {
            console.log("Timed replies set to on");
            // set to on
        }
    }

Upvotes: 0

Views: 68

Answers (1)

MrMythical
MrMythical

Reputation: 9041

Just change the value directly!

something.json

{
  arr: ['str1', 'str2', 'str3'],
  timedStatus: false
}

As you can see, that’s the JSON file (I don’t know exactly what it looks like though)

Here we will use the fs module (which requires no installation) to read and write to the file.

const fs = require('fs')
const file = fs.readFileSync('./something.json', 'utf8');
const data = JSON.parse(file)
data.timedStatus = true
fs.writeFileSync('./something.json', JSON.stringify(data))

Upvotes: 1

Related Questions