我正在编写JSON并将其添加到文件中
但是我的问题是,附加相同的值并过度使用
执行脚本时,我需要将新值添加到文件中并且不要覆盖
我正试图从文件中读取现有的JSON数组,然后用Javascript附加到它,然后将整个内容写回到文件中
需要帮助,谢谢
var obj = {
table: []
};
obj.table.push({"executionDate":date,
"issueID":key,
"priority":{
"jira": priority,
"computed":score1
},
"expectedValue":{
"jira": expected,
"computed":score2
}
})
var json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json, 'utf8', function (err) {
if (err) console.error(err)
});
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({"executionDate":date,
"issueID":key,
"priority":{
"jira": priority,
"computed":score1
},
"expectedValue":{
"jira": expected,
"computed":score2
}
}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', function (err) {
if (err) console.error(err)
}); // write it back
}});
实际结果:
[{
"executionDate": 25 / 03 / 2019,
"issueID": 1,
"priority": {
"jira": important,
"computed": 10
},
"expectedValue": {
"jira": expected,
"computed": 20
}
},
{
"executionDate": 25 / 03 / 2019,
"issueID": 1,
"priority": {
"jira": important,
"computed": 10
},
"expectedValue": {
"jira": expected,
"computed": 20
}
}]
预期结果:
[{
"executionDate": 25 / 03 / 2019,
"issueID": 1,
"priority": {
"jira": important,
"computed": 10
},
"expectedValue": {
"jira": expected,
"computed": 20
}
},
{
"executionDate": 26 / 03 / 2019,
"issueID": 2,
"priority": {
"jira": important,
"computed": 20
},
"expectedValue": {
"jira": expected,
"computed": 30
}
}]