提问者:小点点

node.js将json附加到未使用数组的json文件中


我试图用FS将数据追加到一个没有使用数组的JSON文件中。 该文件需要如下所示:

{"roll.705479898579337276.welcomemessage":"There is a welcome message here", "roll.726740361279438902.welcomemessage":"This is a welcome message for a different server"}

我已经设法让它写入第一位,但它结束了文件,使用fs.appendfile会导致以下情况:

{"roll.705479898579337276.welcomemessage":"There is a welcome message here"}{"roll.726740361279438902.welcomemessage":"This is a welcome message for a different server"}

这会导致EOF错误。 该文件需要像上面的例子那样进行布局,因为我需要以特定的方式访问它。

此代码:

fs.readFile('welcomemessages.json', function (err, readData) {
        var json = JSON.parse(readData);
        json.push(dataToWrite);
        fs.writeFile('welcomemessages.json', JSON.stringify(json), (err) => {
            if (err) {
                throw err;
            }
        });
    })

如果JSON文件被设置为数组,则可以工作,但是我无法像需要的那样与它进行交互。 这简直把我逼疯了,因为我已经这么做了大约两周了,我对谷歌上的每一个链接都感到厌烦:要么不工作,要么做一些我根本不想做的事情。 任何帮助都将不胜感激。


共1个答案

匿名用户

fs.readFile('welcomemessages.json', function (err, readData) {
        var json = JSON.parse(readData);
        for (let property in dataToWrite) {
            json[property] = dataToWrite[property];
        }
        fs.writeFile('welcomemessages.json', JSON.stringify(json), (err) => {
            if (err) {
                throw err;
            }
        });
    })

上面的代码假设您的文件保存为JSON对象而不是数组。 然后它遍历dataToWrite对象的属性,并将它们复制到json对象,json对象应该以您想要的格式保存。 注意我遍历dataToWrite对象属性的方式,即anobject.aprop===anobject[“aprop”]