Add object to json file - Node.js

2024/2/27 7:04:42

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"}


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 arrayfor (i=0;i < obj.length; i++) {// Check each id against the newThingif (obj[i].id !== {found = false;console.log('thing ' + obj[i].id + ' is different. keep going.');}else if (obj[i].id =={found = true;console.log('found it. stopping.');break;}}// if we can't find it, append it to the fileif(!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?


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

Related Q&A

Why does appendChild moves a node?

Im playing around with native javascript. Im basically practicing basic node manipulations such -- add, remove, move, copy, and create.While testing move, I got a question. …

Firefox WebExtension: How Do I Run Code Prior to Disable/Uninstall?

I have recently converted a GreaseMonkey script of mine into a WebExtension, just to get a first impression of the process. Now I have a reached a point where it would be nice to do some clean-up or si…

Three.js outlines

Is it possible to have an black outline on my 3d models with three.js? I would have graphics which looks like Borderlands 2. (toon shading + black outlines)

Can you pass URL parameters to a Javascript file?

<script src="myscript.js?someParameter=123"></script>From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side…

window.history.back() shows Document Expired page, any way around that?

Client is asking for the ability for users to go back to a page full of search results after clicking on a result. Right now its a simple jQuery call:$(a.detail-back-button).on(click, function(evt) {e…

How to manually rerun formatter chain in angularjs directive with ngModel?

Angular.js ngModel has the ability to declare a chain of parsers and formatters. Some more details can be found at the great answer to How to do two-way filtering in angular.js?now the formatter chain…

google chart slantedText and min Value is not working

I am using google chart. I want to slate text on x-axis and should be minimum value is 0 in y-axis. After some google i put some snippet not it working.Here is my code:-var data = google.visualization.…

jQuery save toggleClass in cookie or localStorage

I am trying to save a cookie or use localStorage (whichever is better) to remember when a visitor has clicked on a plus button to show/hide a div. Can anyone assist in helping make the below code work …

Javascript check if each element of an object array is contained in another array

I ave two arrays with objects in themvar requiredfileds=[{name:CVR, value:cvr_code},{name:NODE POINT VAL, value:node_point_val},]The second arrayvar results = [{name:CVB, data:[12,11,233,445]}{name:CVR…

Filtering array with underscore.js

I am trying to filter some objects in my attempt to understand JS better and Im using underscore.jsI come from a C# background and am used to LINQ however underscore is not quite the same.Can you help …