Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add to an existing json file in node.js

Tags:

I am new to Node.js and JavaScript. I have a results.json file that I want to keep a running log of results from a script that pulls images from the web. However, my current script only overwrites the existing result. How do I build upon or add to the results.json so each subsequent result is logged in the results.json file? I would like it to be valid json.

Here is general example:

var currentSearchResult = someWebSearchResult var fs = require('fs'); var json = JSON.stringify(['search result: ' + currentSearchResult + ': ', null, "\t"); fs.writeFile("results.json", json); 

And the results.json:

[     "search result: currentSearchResult" ] 
like image 348
mmryspace Avatar asked Mar 18 '16 19:03

mmryspace


People also ask

How do you add data to an existing JSON object in node JS?

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. We have to read the data, parse, append, and then overwrite the original file because of the JSON format.

How do I add to an existing JSON file?

Steps for Appending to a JSON FileRead the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

How do you append values in node JS?

To append data to file in Node. js, use Node FS appendFile() function for asynchronous file operation or Node FS appendFileSync() function for synchronous file operation.


1 Answers

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)) }) 
like image 87
Daniel Diekmeier Avatar answered Sep 25 '22 06:09

Daniel Diekmeier