0

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.

1
  • Your function is incomplete, it doesn't make any changes to the json. You need something like nameAtTheTime.name = name to assign the property. You then need to return the nameAttheTime object to the function caller to do something else, or write it back to a file. Commented Jan 4, 2023 at 16:28

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

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.