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
}
2
  • 1
    I think you should write the changes to the file stackoverflow.com/questions/36856232/… Commented Nov 23, 2020 at 3:14
  • @IzzyEngelbert I believe that is the basis of Harshana Smith's answer Commented Nov 23, 2020 at 19:02

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

I assume for remove, I do the same fs.writeFileSync code?
Yes. You have to do that
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.