英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论