Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将对象添加到json文件-Node.js_Javascript_Json_Node.js_Jsonobject - Fatal编程技术网

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

Javascript 将对象添加到json文件-Node.js,javascript,json,node.js,jsonobject,Javascript,Json,Node.js,Jsonobject,我试图将一个对象添加到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 = requi

我试图将一个对象添加到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!');
    });
  }
})
var fs=require('fs');
var jf=require('jsonfile')
var util=require('util')
var file='example.json'
//示例新对象
var newThing={
id:324,
文本:“更多文本”
}
//读文件
readFile(文件,函数(err,obj){
//循环遍历数组中的所有对象
对于(i=0;i

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

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

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

对于我的项目,我最终使用了这段代码

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

这对于小文件来说是正确的解决方案,但是如果文件很大呢?是的,文件很大。我将编辑我的问题来指定。如果你的文件很大,它应该由记录或其他东西来分隔行。否则,它将变得难以管理,您必须像正在尝试的那样进行有趣的黑客操作。此外,您用来读取此文件的包无论如何都会读取整个内容。如果要插入记录,应将其推入已从文件解析的现有数组中:
obj.push(newThing)@sanjaypoyzer我没意识到你的问题中有一部分是你一直坚持的。在任何情况下,你都应该将其作为自己的答案发布,并接受自己的问题答案。