我试图将一个对象添加到Node.js中的一个非常大的JSON文件中(但前提是该id与现有对象不匹配)。到目前为止我所拥有的:
示例JSON文件:
[
{
id:123,
text: "some text"
},
{
id:223,
text: "some other text"
}
]
app.js
var fs = require('fs');
var jf = require('jsonfile')
var util = require('util')
var file = 'example.json'
// Example new object
var newThing = {
id: 324,
text: 'more text'
}
// Read the file
jf.readFile(file, function(err, obj) {
// Loop through all the objects in the array
for (i=0;i < obj.length; i++) {
// Check each id against the newThing
if (obj[i].id !== newThing.id) {
found = false;
console.log('thing ' + obj[i].id + ' is different. keep going.');
}else if (obj[i].id == newThing.id){
found = true;
console.log('found it. stopping.');
break;
}
}
// if we can't find it, append it to the file
if(!found){
console.log('could not find it so adding it...');
fs.appendFile(file, ', ' + JSON.stringify(newTweet) + ']', function (err) {
if (err) throw err;
console.log('done!');
});
}
})
这是所以接近我想要的。唯一的问题是JSON文件末尾的尾随]
字符。有没有办法使用文件系统API或其他东西删除它?或者有更简单的方法来完成我想要的工作吗?
答案 0 :(得分:13)
处理此问题的正确方法是解析JSON文件,修改对象并再次输出。
var obj = require('file.json');
obj.newThing = 'thing!';
fs.writeFile('file.json', JSON.stringify(obj), function (err) {
console.log(err);
});
答案 1 :(得分:2)
对于我的项目,我最终使用了这段代码。
function appendJsonToFile(file, entry, key, callback){
if(!_.isObject(entry)){
return callback('Type object expected for param entry', null);
}
fs.readFile(file, 'utf8', function(err, data){
if(err){
return callback(err, null);
}
var json;
try{
json = JSON.parse(data);
} catch(e){
return callback(e, null);
}
if(!_.isArray(json[key])){
return callback('Key "' + key + '" does not point to an array', null);
}
json[key].push(entry);
fs.writeFile(file, JSON.stringify(json), function (err) {
if(err){
return callback(err, null);
}
callback(null, file);
});
});
}