向 JSON 文件中添加对象 - Node.js

4
我将尽力为您进行翻译。以下是需要翻译的内容:

我正在尝试在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或其他方式删除它?或者有没有更简单的方法来实现我想要的目标?

2个回答

15

正确的处理方式是解析JSON文件,修改对象,然后再次输出。

var obj = require('file.json');
obj.newThing = 'thing!';
fs.writeFile('file.json', JSON.stringify(obj), function (err) {
  console.log(err);
});

@sanjaypoyzer,如果你的文件很大,你不应该像你现在这样读取整个内容到内存中。因此,在考虑如何将记录附加到这样的文件之前,您应该考虑如何确定记录ID是否已经存在。jsonfile模块仍然会将整个文件加载到内存中,所以您在这个阶段就有了问题。如果您已经能够负担将整个文件加载到内存中,那么Brad的解决方案将对您有所帮助。 - Darin Dimitrov
@sanjaypoyzer 啊,那么它就正常工作了。它读取了文件并输出了它。你添加了一些代码来修改你的数据? - Brad
1
如果您想要插入记录,您应该将其推送到从文件解析出来的现有数组中:obj.push(newThing); - Darin Dimitrov
好的,是的,现在使用推送功能可以了!谢谢你们两个。 - suryanaga
1
@sanjaypoyzer 我没有意识到你在问题中卡住了那一部分。无论如何,你应该将其发布为自己的答案,并接受自己的答案作为你的问题的解决方案。 - Brad
显示剩余7条评论

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);
            });
        });
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接