javascript 将对象添加到 json 文件 - Node.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28661281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:20:00  来源:igfitidea点击:

Add object to json file - Node.js

javascriptjsonnode.jsjsonobject

提问by sanjaypoyzer

I'm trying to add an object to a very large JSON file in Node.js (but only if the id doesn't match an existing object). What I have so far:

我正在尝试将一个对象添加到 Node.js 中的一个非常大的 JSON 文件中(但前提是 id 与现有对象不匹配)。到目前为止我所拥有的:

example JSON file:

JSON 文件示例:

[
  {
    id:123,
    text: "some text"
  },
  {
    id:223,
    text: "some other text"
  }
]

app.js

应用程序.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!');
    });
  }
})

This is soclose to what I want. The only problem is the trailing ]character at the end of the JSON file. Is there a way to delete it using the file system API or something? Or is there a much easier way to do exactly what I want?

这与我想要的非常接近。唯一的问题是]JSON 文件末尾的尾随字符。有没有办法使用文件系统 API 或其他方法删除它?或者有没有更简单的方法来做我想做的事?

回答by Brad

The proper way to handle this is to parse the JSON file, modify the object, and output it again.

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

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

回答by ChrisRich

For my project I ended up using this code.

对于我的项目,我最终使用了此代码。

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