如何从JSON文件中删除信息?

时间:2019-04-30 00:14:59

标签: javascript node.js json discord.js

我正在尝试让用户创建命令创建器! 目前,这部分工作正常。现在,我需要一种删除它的方法,但我不知道该怎么做。

const fs = require('fs');

module.exports = {
  name: 'delete',
  execute(message, args) {
    if (args.length < 1) {
      return message.reply('Please add more params! !delete <commandName>');
    }
    var data = fs.readFileSync('commands.json', 'utf8');
    var cmds = JSON.parse(data);
    var cmd = cmds.commands;
    try {
      var i, jsonCmd, jsonMsg;
      for (i = 0; i < cmd.length; i++) {
        jsonCmd = cmd[i].name;
        if (args[0] === jsonCmd) {
          delete cmd[i];
          return message.channel.send(message.author + " Command " + jsonCmd + " deleted!");
        }
      }
    } catch (err) {
      console.log(err);
    }
  },
};

JSON文件

{
  "commands":
    [
      { "name": "test2", "message": "test2" },
      { "name": "test3", "message": "test3" },
      { "name": "test4", "message": "test4" },
      { "name": "test5", "message": "test5" },
      { "name": "true", "message": "\\<:LULW:572545743798140940>" },
      { "name": "space", "message": "this message has spaces" }
    ]
}

1 个答案:

答案 0 :(得分:0)

如果要从JSON文件中删除它,则必须添加一个 删除后fs.writeFileSync("commands.json", JSON.stringify(cmds));