javascript - 如何:将新的 json 内容添加到数组中遵循相同格式的预先存在的文件中
问题描述
我在服务器端使用 Node.js,并已将 json 对象从客户端传回服务器。我已将数据添加到预先存在的 gfile 的末尾,但我希望将数据添加到文件的电气Assest 部分下。
这是服务器端的 JSON 文件,我想将数据添加到其中。
{
"substation": [
{
"id": "1",
"geoLocation": "-33.7490, 84.3880",
"supportAssetTypes": [
{
"id": "cs-1",
"type": "capacitorStructure",
"specifications": {
"construction": "galvanized steel",
"capacity": {
"x": 10,
"y": 2,
"z": 5
}
}
}
],
"electricalAssetTypes": [
{
"id": "siemens-c1",
"type": "capacitor",
"specifications": {
"manufacture": "siemens",
"model": "1234",
"shape": "box",
"technology": "internally fused",
"ratedVoltage": 15,
"frequency": [
50,
60
],
"ratedPower": [
{
"kvar": 1000,
"frequency": 50
},
{
"kvar": 1200,
"frequency": 60
}
],
"maxCurrent": "180",
"BIL": [
95,
125,
150,
170,
200
],
"dielectric": "Polypropylene film and oil",
"impregnant": "Biodegradable PCB-free oil",
"dischargeResistor": [
"75 V/10 min",
"50 V/5 min"
],
"losses": 0.2,
"temperatureRange": [
-50,
55
]
}
}
],
"supportAssets": [
{
"id": "struct121",
"type": "cs-1",
"location": {
"x": 1,
"y": 1,
"z": 1
}
}
],
"electricalAssets": [
{
"id": "c1",
"assetType": "siemens-c1",
"radioChs": [
101
],
"installation": {
"supportAssetId": "struct121",
"slot": {
"x":"1",
"y":"1",
"z":"1"
}
},
"mounting": "horizontal"
},
{
"id": "c2",
"assetType": "siemens-c1",
"radioChs": [
102
],
"installation": {
"supportAssetId": "struct121",
"slot": {
"x":"2",
"y":"1",
"z":"1"
}
},
"mounting": "horizontal"
}
]
}]}
这是调用将对象以长字符串添加到文件末尾的函数。
router.post('', function(req, res, next) {
const token = req.headers['authorization'];
//const secretOrKey = 'your_jwt_secret';
if (!token) {
return res.status(401).send({auth: false, message: 'No token provided.'});
}
jwt.verify(token, 'your_jwt_secret', function(err, decoded) {
if (err) {
return res.status(401).send({auth: false, message: 'Failed to authenticate token.'});
}
else {
if (decoded.role === 'admin' || decoded.role === 'engineer') {
fs.readFile('configDB/configuration.json', (err, data) => {
if (err) throw err;
let json = JSON.parse(data);
let object = JSON.stringify(req.body);
//json.push('new capCan: ' + object);
fs.appendFile("configDB/configuration.json", JSON.parse(JSON.stringify(object)), function(err){
if(err) throw err;
console.log(object);
res.send({ status: 'success'});
});
})
}
else {
return res.status(500).send({admin: false, message: 'unauthorized to edit file'});
}
}
})
该代码现在可以工作,但只是在最后一个“}”之后将代码添加到文件的最后。我希望它以相同的格式位于electricalAssets 部分中。
解决方案
推荐阅读
- java - 使用 Vaadin 视图进行 Spring 注入
- python - 将 .py 文件转换为可执行文件后出现“无法执行脚本错误”
- javascript - Javascript toLocalDateString 在 windows 和 mac 上输出不同的格式
- jmeter - 它的负载是多少?
- firebase - 为什么 Firebase Cloud Function 部署后会比在模拟器中慢得多,除了冷启动?
- c# - 如果某事为真,我如何执行代码,无限期地继续执行代码,但停止评估 if 语句?
- mysql - 按大小和日期轮换 MySQL 错误日志的最佳方法
- javascript - 快速会话 - 在另一个选项卡上打开链接后会话丢失
- php - php - 仅计算子文件夹级别的文件,每个文件夹的回显总数
- javascript - 使用带有 express 和 ejs 的套接字 io