首页 > 解决方案 > 从以下元素写入 JSON 文件夹

问题描述

我想知道如何读取/写入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}

标签: javascriptjsondiscord.jsfs

解决方案


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

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

尝试这样的事情:

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");
            }
        });
    }
});

希望这会有所帮助,祝你好运。


推荐阅读