gpt4 book ai didi

javascript - 将数组保存到 JSON 文件,然后使用 Array.push() 将数据保存在其中

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:55 31 4
gpt4 key购买 nike

我正在创建一个日历程序,我的目标是将事件等保存在一个 JSON 文件中。我认为最好的方法是将数组存储在 JSON 文件中的数组中(这样我可以遍历每个数组并在程序启动时加载它们)。

首先也是最重要的:如何将数组推送到 JSON 中的数组中?有什么建议么?举例来说,我有变量 var event 等于数组 {"id": elementTitle, "year": year, "month": month, "day": day}; 将被 JSON.stringify(event) 编辑。那么如何将其保存到已在 JSON 文件中创建的数组中呢?:events = { }

顺便说一下,这个程序是用 electron api 创建的,也使用了 node.js。

最佳答案

你可以这样做。

使用 [] 声明事件,表示它是一个数组。

//文件.json

{
"events":[]
}

使用节点文件系统或“fs”模块,您可以读取和写入您的文件。下面的示例使用异步读取和写入,因此应用程序不会停止和等待 - 但您也可以同步执行此操作。

//应用程序.js

let fs = require('fs');

fs.readFile('/path/to/local/file.json', 'utf8', function (err, data) {
if (err) {
console.log(err)
} else {
const file = JSON.parse(data);
file.events.push({"id": title1, "year": 2018, "month": 1, "day": 3});
file.events.push({"id": title2, "year": 2018, "month": 2, "day": 4});

const json = JSON.stringify(file);

fs.writeFile('/path/to/local/file.json', json, 'utf8', function(err){
if(err){
console.log(err);
} else {
//Everything went OK!
}});
}

});

More examples

关于javascript - 将数组保存到 JSON 文件,然后使用 Array.push() 将数据保存在其中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49118572/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com