尝试保存在JSON文件中时出现“在”附近解析时JSON输入意外结束”的错误

时间:2019-04-17 10:21:16

标签: javascript node.js json

我当前正在尝试将Discord bot的所有命令保存在JSON文件中,但是当我尝试添加多个命令时,应用程序崩溃并抛出错误“ JSONError:解析时JSON输入意外结束在projects \ discordbot \ commands.json中的“”附近

我已经尝试打印出JSON。 添加第一个命令后,commands.json文件如下:

{
  "help": {
    "description": "Displays the help",
    "allowUser": true
  }
}

当我现在加载下一个命令时,它到达了加载JSON文件的地步,但是应用程序崩溃了。

我添加命令的功能:

createCommand: (command, description, allowUser) => 
    {
        console.log("createCommand: " + command);
        let cmds = loadJson.sync(__dirname + "/commands.json");
        if(!cmds.hasOwnProperty(command)) cmds[command] = {
            "description": description,
            "allowUser": allowUser
        };
        console.log(JSON.stringify(cmds, undefined, 2));
        fs.writeFile(__dirname + "/commands.json", JSON.stringify(cmds, undefined, 2), (err) => {});
    },

我在这里加载命令:

loadCommands: () => //Add your own commands here and handle them in the index.js file
    {
        const createCmd = module.exports.createCommand;
        createCmd("help", "Displays the help", true);
        createCmd("cleanup", "Cleans up the channel", false);
        /*createCmd("poke", "Pokes the bot", true);
        createCmd("admins", "Shows a list of staff", true);
        createCmd("developer", "Shows the developer", true);
        createCmd("userinfo", "Shows info about a given user", true);
        createCmd("warn", "Warns a given user", false);
        createCmd("unwarn", "Unwarns a given user", false);
        createCmd("feed", "Checks if a given user is feeding", true);
        createCmd("kick", "Kicks a given user", false);
        createCmd("ban", "Bans a given user", false);*/
    },

1 个答案:

答案 0 :(得分:0)

更换后未发现问题

loadJson.sync(__dirname + "/commands.json");

使用

require(__dirname + "/commands.json");