从以下元素写入 JSON 文件夹

write to a JSON folder from the following element

我想知道如何 read/write from/to json 文件。

const Discord = require ('discord.js');
const client = new Discord.Client();
const {prefix, token,} = require('./config.json');
const fs = require ('fs');

    client.login(token)

        client.on('message', message => {
        if(message.content.startsWith(prefix + "TC")) { //TC = team create

                var args = message.content.split(' ').join(' ').slice(4);
                if(!args) return message.channel.send("No")

                var TeamCreate = `{"NameTeam": "${args}", "ManagerTeam": ${message.author.id}}`

            fs.writeFile("./team.json", TeamCreate, (x) => {
                if (x) console.error(x)
              })}});

json 文件将显示: {"NameTeam": "teste","ManagerTeam": 481117441955463169}

我希望每次下订单时,它都会添加到 json 文件中。

示例:

1 first order = {"NameTeam": "teste","ManagerTeam": 481117441955463169}
2 second order = {"NameTeam": "teste","ManagerTeam": 481117441955463169}, {"NameTeam": "teste2","ManagerTeam": 1234567890}

据我了解,您想创建一个 json 包含团队列表的文件。

最简单的方法是读取和解析 json,对其进行更改,然后将 json 字符串化并更新文件。另外,用字符串制作 json 真的很乱,可能会导致语法错误,而在 javascript 中将 js 对象变成 json 就像做 JSON.stringify(javascriptObject)[=13= 一样简单]

尝试这样的事情:

const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token, } = require('./config.json');
const fs = require('fs');

client.login(token)

client.on('message', message => {
    if (message.content.startsWith(prefix + "TC")) { //TC = team create

        var args = message.content.split(' ').join(' ').slice(4);
        if (!args) return message.channel.send("No")

        var team = {
            NameTeam: args,
            ManagerTeam: message.author.id
        }

        fs.readFile("./team.json", (err, data) => {
            if (!err && data) {
                var parsedJson;
                try {
                    parsedJson = JSON.parse(data);
                    //Make sure the parsedJson is an array
                    if (!(parsedJson instanceof Array)) {
                        parsedJson = [];
                    }
                }
                catch (e) {
                    console.log("Couldn't parse json.");
                    parsedJson = [];
                }
                finally {
                    //Add the newly created team to parsedJson
                    parsedJson.push(team);

                    //Write file, stringifying the json.
                    fs.writeFile("./team.json", JSON.stringify(parsedJson), (err) => {
                        if (!err) {
                            console.log("Successfully created team.");
                        }
                        else {
                            console.log("Error writing to file.")
                        }
                    });
                }
            }
            else {
                console.log("Error reading json");
            }
        });
    }
});

希望这对您有所帮助,祝您好运。