通过编辑文件更改 JSON 到 Node.js 中的对象值

Changing an objects value in JSON trough Node.js by editing the file

我不知道如何在某个地方写字?我想写在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);