0

I'm attempting to make a command that will store an array of strings, and because I don't like to do have the chance of losing everything due to the process restarting, I've decided to use a JSON file array. So far, I've been able to write to the file and add array. However, my roadblock is attempting to modify that array and have the file update with it. Whenever I attempt to .push to the array, it does add the string, just not to the file. So I pose the question: Is it possible to modify an array, located in a JSON file? Snippets of code are below

const database = require('../../characters.json')

const charArray = database[message.author.id]
switch(args[0].toLowerCase()) {
  case "add":
    charArray.push(`${args.slice(1).join(" ")}`)
    break;
  case "view":
    // This code works
  case "remove":
    let pos = charArray.indexOf(`${args.slice(1).join(" ")}`)
    charArray.splice(pos, 1)
    break;
  default:
    // This code works
}
Coder Tavi
  • 449
  • 4
  • 12

2 Answers2

2

You have to write into the JSON file in order to modify the array inside it. For that, you can use NodeJS fs library. Check the code below:

const fs = require('fs');
const database = require('../../characters.json')

const charArray = database[message.author.id]
switch(args[0].toLowerCase()) {
  case "add":
    charArray.push(`${args.slice(1).join(" ")}`)
    database[message.author.id] = charArray;
    fs.writeFileSync('../../characters.json', JSON.stringify(database));
    break;
  case "view":
    // This code works
  case "remove":
    let pos = charArray.indexOf(`${args.slice(1).join(" ")}`)
    charArray.splice(pos, 1)
    break;
  default:
    // This code works
}
Harshana
  • 5,151
  • 1
  • 17
  • 27
0

You will have to rewrite your whole json file everytime you do a mutation.

kigiri
  • 2,952
  • 21
  • 23