If this JSON file won't become too big over time, you should try:
Create a JavaScript object with the table array in it
var obj = { table: [] };Add some data to it, for example:
obj.table.push({id: 1, square:2});Convert it from an object to a string with
JSON.stringifyvar json = JSON.stringify(obj);Use fs to write the file to disk
var fs = require('fs'); fs.writeFile('myjsonfile.json', json, 'utf8', callback);If you want to append it, read the JSON file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { obj = JSON.parse(data); //now it an object obj.table.push({id: 2, square:3}); //add some data json = JSON.stringify(obj); //convert it back to json fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back }});
This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.
UPDATE:
Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.
Answer from kailniris on Stack OverflowIf this JSON file won't become too big over time, you should try:
Create a JavaScript object with the table array in it
var obj = { table: [] };Add some data to it, for example:
obj.table.push({id: 1, square:2});Convert it from an object to a string with
JSON.stringifyvar json = JSON.stringify(obj);Use fs to write the file to disk
var fs = require('fs'); fs.writeFile('myjsonfile.json', json, 'utf8', callback);If you want to append it, read the JSON file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { obj = JSON.parse(data); //now it an object obj.table.push({id: 2, square:3}); //add some data json = JSON.stringify(obj); //convert it back to json fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back }});
This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.
UPDATE:
Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.
Please try the following program. You might be expecting this output.
var fs = require('fs');
var data = {}
data.table = []
for (i=0; i <26 ; i++){
var obj = {
id: i,
square: i * i
}
data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
if (err) throw err;
console.log('complete');
}
);
Save this program in a javascript file, say, square.js.
Then run the program from command prompt using the command node square.js
What it does is, simply overwriting the existing file with new set of data, every time you execute the command.
Happy Coding.
How to add data to a JSON file in JavaScript?
Add object to json file - Node.js
How do I append to an array inside a json file in node?
Appending Data to JSON File in Node.js Without Overwriting - Ask a Question - TestMu AI Community
Videos
If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.
var fs = require('fs')
var currentSearchResult = 'example'
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
json.push('search result: ' + currentSearchResult)
fs.writeFile("results.json", JSON.stringify(json))
})
In general, If you want to append to file you should use:
fs.appendFile("results.json", json , function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
Append file creates file if does not exist.
But ,if you want to append JSON data first you read the data and after that you could overwrite that data.
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data);
json.push('search result: ' + currentSearchResult);
fs.writeFile("results.json", JSON.stringify(json), function(err){
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
})
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);
});
});
}
» npm install jsonfile
I’m working on a chat client and server to learn about API’s and now I need to write the messages submitted by users into the master chat log (a json file with a messages array inside of it). I have been searching for different approaches and they all error out somehow. I’m using node and express for routing if that helps.
tldr; how should one append an object to an array inside a json file using node.
edit: I’ve taken carcigenocate’s advice. I open the file, make the changes in memory, then write to the file and reload it to reflect changes. I am still open to improvements on this design!
Try this. Don't forget to define anchors array.
var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);
fs.writeFile("testOutput.json", JSON.stringify(json))
I created two small functions to handle the data to append.
- the first function will: read data and convert JSON-string to JSON-array
- then we add the new data to the JSON-array
- we convert JSON-array to JSON-string and write it to the file
example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,
it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
the full code is here :
const fs = require('fs');
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
async function append_data (filename , data ) {
if (fs.existsSync(filename)) {
read_data = await readFile(filename)
if (read_data == false) {
console.log('not able to read file')
}
else {
read_data.push(data)
dataWrittenStatus = await writeFile(filename, read_data)
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
else{
dataWrittenStatus = await writeFile(filename, [data])
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
}
async function readFile (filePath) {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return JSON.parse(data)
}
catch(err) {
return false;
}
}
async function writeFile (filename ,writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
return true
}
catch(err) {
return false
}
}