更新 JSON 内容使用 JavaScript。

huangapple go评论78阅读模式
英文:

Update Json content with javascript

问题

Here is the translated portion:

你好,大家,我遇到了一些关于我的 JSON 文件的问题。

文件名是 name.json

{   
    "name": "Gerald"
}

如何使用 JavaScript 中的函数将名字更改为 "Gandalf"

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

我尝试寻找解决方案,但是没有成功。

英文:

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

得分: 1

你可以像这样修改该函数:

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

如果你想要将更改保存到 name.json 文件中,将以下代码添加到 changeNameJson 函数体的末尾:

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

或者,如果你想要使 name.json 文件的内容更美观:

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

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));

huangapple
  • 本文由 发表于 2023年1月4日 22:16:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75006752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定