Markodel
Markodel

Reputation: 9

Update Json content with javascript

Hello guys I got some Problems wiht my Json File

The Filename is name.json

{   
    "name": "Gerald"
}

How can I Change the name to "Gandalf" with a function in Javascript

function changeNameJson(name){
  let filename= "./name.json";
  let file = fs.readFileSync(filename, 'utf8');
  let nameAtTheTime = JSON.parse(file);
  let newName=name;
}

I tried to find a Solution but i couldn't.

Upvotes: 0

Views: 83

Answers (1)

mahooresorkh
mahooresorkh

Reputation: 1444

You can modify the function like this:

function changeNameJson(name){
    let filename= "./name.json";
    let file = fs.readFileSync(filename, 'utf8');
    let nameAtTheTime = JSON.parse(file);
    nameAtTheTime.name = name;
}

And if you want to save the change into name.json file, add this to the end of changeNameJson function body :

fs.writeFileSync("./name.json",JSON.stringify(nameAtTheTime)); 

Or if you want to make name.json file content prettier:

fs.writeFileSync("./name.json",JSON.stringify(nameAtTheTime,null,2));

Upvotes: 1

Related Questions