admin管理员组

文章数量:1220791

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:

example JSON file:

[
  {
    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!');
    });
  }
})

This is so close 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?

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:

example JSON file:

[
  {
    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!');
    });
  }
})

This is so close 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?

Share Improve this question edited Feb 22, 2015 at 19:00 Nivetha T 4811 gold badge4 silver badges17 bronze badges asked Feb 22, 2015 at 18:03 suryanagasuryanaga 4,00212 gold badges37 silver badges49 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

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

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

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

本文标签: javascriptAdd object to json fileNodejsStack Overflow