0

I am working on an nodejs app which reads data from a json file. Now I want to edit this json file in js (write to it). How do I do this ?

Here is my js code: `

var fs = require("fs")

//function for file input
function getFile(filename) {
  var data = fs.readFileSync(filename,"ascii")
  return data }

//parsing json
var jsonString = [getFile("File.json")]
var jsonObj = JSON.parse(jsonString)`
2
  • 1
    A JSON object when parsed is then like any other JS object. Use object dot notation to access any data you want. Commented Aug 12, 2015 at 8:20
  • for addition: jsonObj.key=value, for deletion: delete jsonObj.key Commented Aug 12, 2015 at 8:24

4 Answers 4

5

Modify the jsonObj as you want, create a new object or whatever, then write the file:

fs.writeFileSync("File.json", jsonData);

This will overwrite the file if it exists, so that way you edit the file.

Sign up to request clarification or add additional context in comments.

Comments

3

You can load a json file by requiring it.

var contents = require('/path/to/file.json');

Iterate contents just like a regular object.

Comments

1

A JSON object, when parsed is, like any other JS object. Use object dot notation to access any data you want.

For example a value:

console.log(isonObi.something.value)

For example a value in an array:

console.log(isonObi.something[0].value)

From eyp

Modify the jsonObj as you want, create a new object or whatever, then write the file:

fs.writeFileSync("File.json", jsonData); This will overwrite the file if it exists, so that way you edit the file.

Comments

1

With nodeJS, you can require a JSON file.

Supposing you get this JSON file :

//test.json

[
  {
    "name": "toto",
    "code": "4"
  },
  {
    "name": "test",
    "code": "5"
  }
];

Then, you can require this file and perform some modification :

var json = require('./test.json');

json.forEach(function(elm){
    elm.name = 'test';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.