Javascript 在JSON和don'中追加元素;t覆盖
我正在编写一个JSON并将其添加到一个文件中 但我的问题是附加相同的值和过度渲染 当我执行脚本时,我需要将新值添加到文件中,而不是覆盖 我尝试从文件中读取现有的JSON数组,用Javascript附加到它,然后将整个内容写回一个文件 需要帮助,谢谢Javascript 在JSON和don'中追加元素;t覆盖,javascript,json,Javascript,Json,我正在编写一个JSON并将其添加到一个文件中 但我的问题是附加相同的值和过度渲染 当我执行脚本时,我需要将新值添加到文件中,而不是覆盖 我尝试从文件中读取现有的JSON数组,用Javascript附加到它,然后将整个内容写回一个文件 需要帮助,谢谢 var obj = { table: [] }; obj.table.push({"executionDate":date, "issueID":key, "priority":{ "jira": priority,
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
}
}]
看起来您正在使用相同的值填充在变量中,如score1、score2和data,并将其作为json进行第二次写入。这就是为什么您会看到相同的数据两次的原因。好吧,但问题是变量score1 score 2可能会更改。如果更改,那么它将反映在文件中。我相信您现在的问题是json文件中的数组在两个索引中具有相同的数据。我是对的吗?是的,你是对的,我需要使用这种形式的JSONok,那么只有当变量中存储的数据发生变化时,索引中的数据才会发生变化。因为我看到您使用的是相同的数据并生成对象,所以出现了这个问题。看起来您使用的是相同的值填充在变量中,如score1、score2和data,并将其作为json进行第二次写入。这就是为什么您会看到相同的数据两次的原因。好吧,但问题是变量score1 score 2可能会更改。如果更改,那么它将反映在文件中。我相信您现在的问题是json文件中的数组在两个索引中具有相同的数据。我是对的吗?是的,你是对的,我需要使用这种形式的JSONok,那么只有当变量中存储的数据发生变化时,索引中的数据才会发生变化。因为我看到您使用的是相同的数据并创建对象,所以存在这个问题