首页 > 解决方案 > Issues On JSON File

问题描述

const fs = require('fs');
const express = require('express');

const app = express();

app.use(express.json());

app.get('/submit', (req, res) => {
    let Com_Title = req.query.ComTitle;
    let Com_Text = req.query.ComText;
    let data = {
        Title: Com_Title,
        Text: Com_Text,
    }
    console.log(data);
    let jsonData = JSON.stringify(data);
    // fs.writeFileSync('notes.json', dataJSON)
    // let MyData = JSON.parse(jsonData);
    fs.appendFileSync('ComplaintFile.json', jsonData, err => {
        if (err) {
            console.log(err);
            res.sendStatus(404).end();
        }
        console.log('Data Added');
        res.send('Added');
    })
});

let port = 8080;
app.listen(port, () => {
    console.log("Listening to 8080");
})
{
    "Title": "Canteen Issues",
    "Text": "A paragraph"
}{
    "Title": "Canteen ",
    "Text": "Topic sentences are similar "
}

I have issues on saving data in JSON. Actually is saving the data on JSON file but it have comma issues like if I add one or more data that next data storing without the comma.

Anyone faced this issue?

标签: javascript

解决方案


使用appendfilesync不适合存储这样的 JSON 数据,因为 JSON 是结构化数据,而 appendfilesync 只会将数据添加到文件末尾。你需要:

  1. 读取文件中已有的数据。
  2. 将数据解析为 JSON。
  3. 将新数据添加到 JSON 对象/数组。
  4. 对 JSON 数据进行字符串化。
  5. 将数据保存到文件中。

在此示例中,初始文件如下所示:

[{"Title":"Title","Text":"Content"}]

所以,它是一个数组。然后您可以将对象添加到该数组中。

var fs = require("fs");

fs.readFile("data.json", function(err, buf) {
  let dataStr = buf.toString();
  let dataObj = JSON.parse(dataStr);
  let newData = {Title: "Title", Text: "Content"};
  dataObj.push(newData); // assuming that this is an array

  let newDataStr = JSON.stringify(dataObj);

  fs.writeFile("data.json", newDataStr, (err) => {
    if (err) console.log(err);
    console.log("Successfully Written to File.");
  });
});

推荐阅读