javascript - 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?
解决方案
使用appendfilesync不适合存储这样的 JSON 数据,因为 JSON 是结构化数据,而 appendfilesync 只会将数据添加到文件末尾。你需要:
- 读取文件中已有的数据。
- 将数据解析为 JSON。
- 将新数据添加到 JSON 对象/数组。
- 对 JSON 数据进行字符串化。
- 将数据保存到文件中。
在此示例中,初始文件如下所示:
[{"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.");
});
});
推荐阅读
- python - 如何正确访问和使用烧瓶 sqlalchemy 中的 sqlalchemy 方法
- pandas - 熊猫中的 isnull() 无法识别空白值(Python 编码)
- powerbi - DAX :由于资源内存超出,需要更换 SWITCH
- java - 创建多个新对象时避免冗余代码的最佳方法
- python - 如何使用 Python 或 Selenium 从 Chrome 中的 UI 将文件下载到特定路径项目?
- python - if 和 for 在一行中循环
- salesforce - 大量更新记录
- c# - 如何让 Redis 通知我的服务有关事件
- express - Nrwl Nx build for production 缺少节点模块包
- reporting-services - SSRS 如何使用参数更改分组和列