我不知道如何在某个地方书写?我想写下 ReadData.welcome_message[0] 这个命令指出的位置。
我的database.json文件有这个;
{"faqs":["Birkere bir?","bir"],"welcome_message": ["welcome"]}
并且ReadData.welcome_message[0]
指出欢迎
const fs = require('fs'); //imports node.js FileSystem
const ReadDatabase = fs.readFileSync('database.json'); //reads the file in synchronized way
const ReadData = JSON.parse(ReadDatabase); //parses bits so it can be readable
//These three for me to understand what is where
console.log(ReadData.faqs[0]);
console.log(Object.keys(ReadData));
console.log(ReadData.welcome_message[0]);
let edited_welcome = JSON.stringify(edited_message);
fs.writeFileSync('database.json', edited_welcome)//I understand this is the way to write to the file
//console.log('"' +edited_message + '"'); //did help me understand if my code worked
});
最佳答案
您可以根据需要进行更新,如下所示:
const ReadDatabase = fs.readFileSync('database.json'); //reads the file in synchronized way
const ReadData = JSON.parse(ReadDatabase); //parses bits so it can be readable
//These three for me to understand what is where
console.log(ReadData.faqs[0]);
console.log(Object.keys(ReadData));
console.log(ReadData.welcome_message[0]);
ReadData.welcome_message[0] = 'New Welcome Message'; // Modify as you need!
let edited_ReadData = JSON.stringify(ReadData);
console.log('Updated database.json: ', edited_ReadData);
fs.writeFileSync('database.json', edited_ReadData);
关于javascript - 通过编辑文件来通过 Node.js 更改 JSON 中的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51207196/