【问题标题】:Writing JSON data to a JSON file and reading using FS将 JSON 数据写入 JSON 文件并使用 FS 读取
【发布时间】:2021-08-22 23:41:58
【问题描述】:

基本上,我有代码将 json 数据添加到我拥有的特定 json 文件中。代码本身正在运行,但我希望它在 json 文件的表中实现。我还希望能够读取json文件中的信息(具体看它有什么id,如果message.author有那个id,然后返回一条消息说它被禁止以及原因)

注意:此代码的目的是在 Discord 平台上使用 discord.js 库。

JSON 文件:

{
    "bans": [
        {
        "id": "218931839123128",
        "reason": "yes"
    },
    {
        "id": "273618444",
        "reason": "no"
    }
]
}

代码:

        let format = {
                "id": target, //args[0]
                "reason": reason //args[1]
        }

fs.appendFile('banlist.json', JSON.stringify(format), function (err) {
  if (err) throw err;
  message.channel.send("Added.")
  console.log('Saved!');
});

【问题讨论】:

  • 你的问题是什么?
  • 你能解释一下你到底想开发什么。
  • 这是一个禁止系统检查message.author是否有这个id。如果有,机器人将返回一条消息,说明他无法使用该命令的原因。我创建了一个类似“banfrombot”的命令,并输入了 id(args[0]) 和 reason(args[1]),所以我想在 bans 表中写入 json 文件。

标签: javascript node.js json discord.js fs


【解决方案1】:

为了将对象附加到 JSON 文件中的数组,您可能需要执行以下操作:

  1. 读取 JSON 文件
  2. 将 JSON 文件解析为 JavaScript 对象
  3. 将您的对象添加到指定的数组中
  4. 将您的对象字符串化为 JSON 字符串
  5. 编写 JSON 文件

fs.appendFile() 将数据添加到文件末尾,可能不是您要查找的内容。

以下是工作代码的示例:

const fs = require("fs");
const dataToAdd = {
  id: "target",
  reason: "reason"
};

// Read the JSON file
const JSONString = fs.readFileSync("./banlist.json", "utf8");

// Parse the JSON file
const JSData = JSON.parse(JSONString);

// Add object to the array
JSData.push(dataToAdd);

// Stringify the data
const newJSONString = JSON.stringify(JSData, null, 2);

// Write the file
fs.writeFileSync("./banlist.json", newJSONString);

比较 JSON 文件中的数据并通知用户被禁止:

  1. 读取 JSON
  2. 解析 JSON
  3. 使用某种算法或循环,检查和比较数据
  4. 如果数据匹配,则输出用户被禁止

【讨论】:

  • 我试过这个方法,但它返回“JSData.push 不是函数”。我该如何解决这个问题?
  • 查看您提供的 JSON 数据,看起来列表位于 JSDATA.bans,所以 JSDATA.bans.push(...) 应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多