Javascript 用节点JS替换文件中的字符
我将JSON附加到一个文件中。我使用appendFile将JSON附加到文件中。 我使用的是特定的JSON结构 我的问题是:如何更改字符']['by',' 我想我需要使用readFile和函数replace 需要帮助,提前谢谢Javascript 用节点JS替换文件中的字符,javascript,json,Javascript,Json,我将JSON附加到一个文件中。我使用appendFile将JSON附加到文件中。 我使用的是特定的JSON结构 我的问题是:如何更改字符']['by',' 我想我需要使用readFile和函数replace 需要帮助,提前谢谢 var table = [] table.push({"executionDate":date, "issueID":key, "priority":{ "jira": priority, "computed":sco
var table = []
table.push({"executionDate":date,
"issueID":key,
"priority":{
"jira": priority,
"computed":score1
},
"expectedValue":{
"jira": expected,
"computed":score2
}
})
var json = JSON.stringify(table);
fs.appendFile('myjsonfile.json', json, 'utf8', function (err) {
if (err) console.error(err)
});
实际结果:
[{
"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
}
}]
预期结果:
[{
"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
}
}]
如果使用append,则无法执行此操作。请阅读第一条注释,以了解如何实现您的目标 在这里,我提出了另一种不符合您预期结果的方法,但在注释中,我无法输入代码块,这就是我将其放在此处的原因 我建议每次添加JSON和换行符时都添加一个“\n””。然后,在阅读文件时,按换行符拆分并分别解析每一行:
var data = contents.trim()
.split(/\n/g)
.map(line => JSON.parse(line)[0]);
也就是说,如果数组中始终只有一项
如果每个附加条目有多个条目:
var data = [];
contents.trim()
.split(/\n/g)
.map(JSON.parse)
.forEach(entry => data.push(...entry));
最后我发现:
var table = []
table.push({"executionDate":date,
"issueID":key,
"priority":{
"jira": priority,
"computed":score1
},
"expectedValue":{
"jira": expected,
"computed":score2
}
})
var json = JSON.stringify(table);
fs.appendFile('myjsonfile.json', json, 'utf8', function (err) {
if (err) console.error(err)
});
fs.readFile('myjsonfile.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace('][',',');
fs.writeFile('myjsonfile.json', result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
您不想附加文件,但需要从文件中推送json数组中的数据,因此您必须读取json,然后扩展数据并将其写回文件。可能重复的是,我看到了这个问题,并尝试执行相同的操作,但我不想覆盖…我需要使用writeFile或appendFile?您不需要带拆分的a/g,并且该文件将不再是json,json文件中现有数据内容的每一行也将不再是json,因此json.parse(line)将抛出exception@Jeremy使用
fs.appendFile('myjsonfile.json',json+“\n”,…)
@AZ\uu您是对的,我的答案并不能解决预期结果中要求的问题(我给了你的评论a+1!)但它是有效的。我一直在使用它。这是JSON的一个反复出现的问题,我不喜欢每次我想附加东西时都读写整个文件。我正在这样做:data=JSON.trim().split(/\n/g).map(line=>JSON.parse(line)[0]);fs.appendFile('myjsonfile.JSON',JSON.stringify(data)+“\n”,“utf8”,函数(呃,{..});