如何在 javascript/nodejs 中将数据附加到具有特定索引的 JSON

我正在做一个基本的“访客簿”功能。

用户可以提交一个小表格(包含三个输入:姓名、消息和表情符号)。

我在我的路由器组件中使用 req.body 获取它。我正在使用带有 express 和 bodyparser 的 nodejs。


我只想将这些数据存储在 JSON 中,不希望这里涉及任何数据库。我在使用“fs”模块的writeFile方法上遇到了麻烦。它可以工作,但会将新数据推送到我的 JSON 文件的单个数组之外。 你知道我是否可以推入阵列内部吗?类似于 .push 方法,但使用writeFile / appendFile / wathever可以很好地处理 json 文件。这是我的代码:



app.post(路由器):


app.post('/visitorBook', async (req, res) => { 

    let formData = {

        name: req.body.name,

        msg: req.body.msg,

        emoji: req.body.emoji

    }

    try {

        console.log(req.body)

        let data = JSON.stringify(formData, null, 2);


        fs.writeFile("./views/scripts/dataVisitorBook.json", data, { { // dataVisitorBook.json is the storage file

            flag:'a' // this flag specify 'please append it' over 'please override file'

        }

        }, (err) => {

            console.log('error :', err)

        });



        res.redirect('/contact') 

    } catch (error) {

        console.error('/visitorBook route error : ', error)

    }

})

我的JSON:


[

    {

        "name": "test1",

        "msg": "test1",

        "emoji": "<i class='fas fa-hippo fa-3x'></i>"

    },

    {

        "name": "test2",

        "msg": "test2",

        "emoji": "<i class='fas fa-hippo fa-3x'></i>"

    }

]



{

  "name": "sd",

  "msg": "sd",

  "emoji": "<i class='fas fa-kiwi-bird fa-3x'></i>"

}

所以最后一个名称和消息中带有“sd”的是推送的。其他 2 个是我手动编写的,用于 readFile 测试。


我希望我提供了所有需要的信息。不习惯在这里发帖...谢谢。


幕布斯7119047
浏览 136回答 3
3回答

跃然一笑

如果您从现有文件中读取并使用 解析它JSON.parse,您将能够实际使用Array.push它。然后你可以将字符串化的结果写回到文件中:fs.readFile("./views/scripts/dataVisitorBook.json", function (err, data) {&nbsp; if (err) throw err;&nbsp; let data = JSON.parse(data.toString('utf8'));&nbsp; data = JSON.stringify(data, null, 2);&nbsp; fs.writeFile("./views/scripts/dataVisitorBook.json", data, { { // dataVisitorBook.json is the storage file&nbsp; &nbsp; &nbsp; flag:'a' // this flag specify 'please append it' over 'please override file'&nbsp; }&nbsp; }, (err) => {&nbsp; &nbsp; &nbsp; console.log('error :', err)&nbsp; });})它可能不是最佳的,因为随着文件变大,它可能需要更多时间。

喵喵时光机

使用 fs.readFileSync 读取文件。然后,我将这个原始数据存储在一个变量中,同时将其解析为 JSON。然后,我将其推送到“jsonBook”变量中,该变量是临时制作成简单对象变量的 json 文件。然后我用 writeFile 写入文件,将数据作为变量“parsed”传递,其中包含我的“jsonBook”的 JSON.stringified 版本app.post("/visitorBook", async (req, res) => {&nbsp; &nbsp; let formData = {&nbsp; &nbsp; &nbsp; &nbsp; name: req.body.name,&nbsp; &nbsp; &nbsp; &nbsp; msg: req.body.msg,&nbsp; &nbsp; &nbsp; &nbsp; emoji: req.body.emoji,&nbsp; &nbsp; };&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; let rawdata = fs.readFileSync("./views/scripts/dataVisitorBook.json");&nbsp; &nbsp; &nbsp; &nbsp; var jsonBook = JSON.parse(rawdata);&nbsp; &nbsp; &nbsp; &nbsp; let formDataParsed = JSON.stringify(formData, null, 2);&nbsp; &nbsp; &nbsp; &nbsp; jsonBook.push(formData);&nbsp; &nbsp; &nbsp; &nbsp; let parsed = JSON.stringify(jsonBook, null, 2);&nbsp; &nbsp; &nbsp; &nbsp; fs.writeFile("./views/scripts/dataVisitorBook.json", parsed, (err) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (err) throw err;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("saved");&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; res.redirect("/contact");&nbsp; &nbsp; } catch (error) {&nbsp; &nbsp; &nbsp; &nbsp; console.error("/visitorBook route error : ", error);&nbsp; &nbsp; }});我希望我说得很清楚。也许我做了一些解释错误,我正在尽力而为。

慕姐4208626

我很欣赏你的简单尝试但是使用一些标准对你来说会更好有一些用于 Node 的标准 JSON DB,例如:&nbsp;Simple JSON DB&nbsp;Node JSON DB&nbsp;另外,您可以尝试 SQLite 我也尝试使用一个简单的 JSON 文件作为 DB。我面临着很多工作,我也做到了。所以我的建议是使用一些标准库除此之外,您必须获取文件数据将其解析为 JSON(解码)进行更改,然后再次将其序列化并写入文件(编码)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript