【问题标题】:How can I write to a JSON file using Javascript?如何使用 Javascript 写入 JSON 文件?
【发布时间】:2018-12-25 21:16:29
【问题描述】:

这是一个 Discord 机器人,所以我使用的是 node.js。

代码更改了变量,因此它只更改了变量而不是文件,这完全有道理,但是我如何能够使用类似的方法更改 JSON 文件

{
  "Tournament": {
    "teamCount": "4",
    "matchCount": "3",
    "Team": [
      {
        "name": "Team1"
      },
      {
        "name": "Team2"
      },
      {
        "name": "Team3"
      },
      {
        "name": "Team4"
      }
    ],
    "Matches": [
      {
        "GameCode": "1111",
        "TeamOne": "Team1",
        "TeamTwo": "Team2",
        "Date": "1/1/2018",
        "Game_Time": "0800",
        "GameStatus": "FALSE"
      },
      {
        "GameCode": "1112",
        "TeamOne": "Team3",
        "TeamTwo": "Team4",
        "Date": "1/1/2018",
        "Game_Time": "1000",
        "GameStatus": "FALSE"
      },
      {
        "GameCode": "1113",
        "TeamOne": "Team1",
        "TeamTwo": "Team4",
        "Date": "1/1/2018",
        "Game_Time": "1000",
        "GameStatus": "FALSE"
      }
    ]
  }
}




case "datechange":
    message.channel.send("Date Before Change: " + file.Tournament.Matches[0].Date);
    cancer.Tournament.Matches.Date = "test";
    message.channel.send("Date Before Change: " + file.Tournament.Matches[0].Date);
break;

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 你能具体解释一下你做了什么,你在哪里卡住了吗?
  • Json 文件是 javascript 对象,所以读取它,修改它,写入它。我会给你举个例子,但我不擅长 JS。
  • 到目前为止,在 switch 案例示例中(如下所示,可能有点难以看到),到目前为止,我只尝试更改日期,但没有奏效,但答案下面可能会有所帮助,请检查一下然后更新你们所有

标签: javascript json node.js discord.js


【解决方案1】:

您只需在变量更改后将更改写入文件。您可以使用fs 并编写这样的函数。

fs = require('fs');

function updateDateInFile(file, index, field, date){
    file.Tournament.Matches[index][field] = date;
    fs.writeFile('fileName.json', JSON.stringify(file));
}

所以你可以这样做,

case "datechange":
    message.channel.send("Date Before Change: " + file.Tournament.Matches[0].Date);
    cancer.Tournament.Matches.Date = "test";
    updateDateInFile(file, 0, 'Date', cancer.Tournament.Matches.Date);
    message.channel.send("Date Before Change: " + file.Tournament.Matches[0].Date);
break;

您不需要在fs.writeFile 之后使用fs.close,因为它不会返回fd(文件描述符)。

【讨论】:

  • 我也可以将日期更改为其他内容,例如游戏时间,对吧?
  • @MuhammadSiddiqui 是的,你可以。我更新了答案。
  • JSON 文件的格式不再像原来那样,全部在一行中
猜你喜欢
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多