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

I am having trouble to figure out that how can I write in a certain place? I want to write where ReadData.welcome_message[0] this command points out.

My database.json file has this;

{"faqs":["Birkere bir?","bir"],"welcome_message": ["welcome"]}

And ReadData.welcome_message[0] points out welcome

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

Upvotes: 2

Views: 1745

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

You can update as you need like this:

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

Upvotes: 2

Related Questions