Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a value in a json file and save it through node.js

Tags:

json

node.js

How do I update a value in a json file and save it through node.js? I have the file content:

var file_content = fs.readFileSync(filename); var content = JSON.parse(file_content); var val1 = content.val1; 

Now I want to change the value of val1 and save it to the file.

like image 686
Nava Polak Onik Avatar asked May 21 '12 13:05

Nava Polak Onik


People also ask

How do I save JSON data in node JS?

To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS's writeFile() function.

How do I change the value of a JSON object?

Array value of a JSON object can be modified. It can be simply done by modifying the value present at a given index. Note: If value is modified at an index which is out of the array size, then the new modification will not replace anything in the original information but rather will be an add-on.


2 Answers

Doing this asynchronously is quite easy. It's particularly useful if you're concerned with blocking the thread (likely). Otherwise, I'd suggest Peter Lyon's answer

const fs = require('fs'); const fileName = './file.json'; const file = require(fileName);      file.key = "new value";      fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {   if (err) return console.log(err);   console.log(JSON.stringify(file));   console.log('writing to ' + fileName); }); 

The caveat is that json is written to the file on one line and not prettified. ex:

{   "key": "value" } 

will be...

{"key": "value"} 

To avoid this, simply add these two extra arguments to JSON.stringify

JSON.stringify(file, null, 2) 

null - represents the replacer function. (in this case we don't want to alter the process)

2 - represents the spaces to indent.

like image 199
Seth Avatar answered Oct 08 '22 15:10

Seth


//change the value in the in-memory object content.val1 = 42; //Serialize as JSON and Write it to a file fs.writeFileSync(filename, JSON.stringify(content)); 
like image 38
Peter Lyons Avatar answered Oct 08 '22 15:10

Peter Lyons