【问题标题】:Remove part of json content移除部分json内容
【发布时间】:2021-11-28 15:04:18
【问题描述】:

我希望在给定时间/日期过去时编辑我的 json 文件。我试过 delete termine[0] 但这不会删除文件的一部分。

我的 json 文件

    [{
    "datum": "2020-10-10T10:00:00",
    "event": "..."
    },
    {
    "datum": "2021-10-10T10:00:00",
    "event": "..."
    },...
    ]

我的代码

let termine = JSON.parse(fs.readFileSync("/home/pi/NeonBot/termine.json", "utf8"))

var now = new Date();
var date = termine[0].datum
    date = new Date(date)

do {
    delete termine[0]
    console.log(`Deleted Event`)
} while (date < now)

【问题讨论】:

  • 您想要修改文件本身吗?然后你需要写回文件。修改读取和解析文件返回的对象不会修改底层文件。
  • @InstanceHunter 这就是问题所在。我可以使用 fs.writeFile() 但不知道如何只删除其中的一部分。

标签: javascript json fs


【解决方案1】:

你有一个无限循环,因为你永远不会在循环中更新date

您还应该在删除之前检查条件,而不是之后。

while (new Date(termine[0].datum_) < now) {
    delete termine[0];
    console.log("Deleted Event");
}

不是一次删除一个元素,而是找到要保留的第一个元素的索引,然后使用splice 删除它之前的所有元素。

let index = termine.findIndex(event => new Date(event.datum) >= now);
if (index > 0) {
    termine.splice(0, index);
}

fs.writeFileSync("/home/pi/NeonBot/termine.json", JSON.stringify(termine), "utf8");

【讨论】:

  • 但是文件仍然没有被编辑。您的回答只编辑了数组。
  • 把它写回文件,我把它添加到答案中。
猜你喜欢
  • 2021-05-11
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
相关资源
最近更新 更多