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

标签 javascript node.js json

我正在尝试向 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 或其他方式删除它?还是有更简单的方法来完全按照我的意愿行事?

最佳答案

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

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

关于javascript - 将对象添加到 json 文件 - Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661281/

相关文章:

node.js - 蒙哥错误: self signed certificate in certificate chain

jquery - 当响应为 json 时,Laravel 响应 id 会发生变化,但转储数据时 id 就在那里

javascript - 访问数据库搜索调用的子对象

javascript - 如何在sequelize中使用数据库时区获取当前日期/时间

node.js - 调试时 NodeJS 无响应(在 VS Code 中)

session - node.js + express.js : session handling with mongodb/mongoose

javascript - 如何使 JQuery Loop 获取不同的图像

php - json_encode,[括号]中需要的关联数组

javascript - 移动优先汉堡菜单不适用于网站的移动版本,但在缩小尺寸时可以使用

javascript - jQuery:外部插件调用选项中的 If 条件