maruan
maruan

Reputation: 67

Write JavaScript object to an array inside a JSON file

How can I write a JavaScript object inside of an array that is inside a JSON file? What I mean is: I'm making a Discord (message app) BOT, when the user uses the command "/add" the BOT will ask for 2 inputs, a "name" and an "artist" both this inputs make up a song so I'm creating an object called "data" for that song. I also have a JSON file, that my database, what I want is, everytime this command is used, my object should the pushed inside of an array in my JSON file, so later on I can retrieve a random object inside of this array. How can I do that? I hope the question is not too confusing, thanks!


module.exports={

data: new SlashCommandBuilder()
    .setName('add')
    .setDescription('Add a song to the database.')
    .addStringOption(option =>
        option.setName('artist')
            .setDescription('The artist of the song')
            .setRequired(true))
        .addStringOption(option =>
                option.setName('name')
                    .setDescription('The name of the song')
                    .setRequired(true)),

            async execute(interaction){
                let name = interaction.options.getString('name');
                let artist = interaction.options.getString('artist');
                
                const data = { name: name, artist: artist};

                await interaction.reply(`**` + artist + `**` + ` - ` + `**` + name + `**` + ` was added to the database.`)},

 };

//WHAT YOU SEE FROM NOW ON IS A DIFFERENT FILE, A JSON FILE CALLED data.json with some examples of what it should look like

[
    {
        "name":"Die for You",
        "artist":"The Weeknd"
    },
    {
        "name":"FEAR",
        "artist":"Kendrick Lamar"
    }
]

Upvotes: 0

Views: 337

Answers (2)

Slidein
Slidein

Reputation: 319

You have to use node filesystem.

Import FS and use writeFile function.

https://nodejs.org/api/fs.html#filehandlewritefiledata-options

  • Dont forget about JSON.stringify to turn your object into string
const fs = require('fs');
const data = { name: name, artist: artist };

fs.writeFile("output.json", JSON.stringify(data), 'utf8', function (err) {
        if (err) {
                console.log("An error occured while writing JSON Object to File.");
                return console.log(err);
        }

        console.log("JSON file has been saved.");
});

// Edit (Adding new objects to .json)

You have to read data from your file, add something and save again.

let rawdata = fs.readFileSync('data.json');
let data    = JSON.parse(rawdata);

data.push({name: name, artist: artist}); 
// to use push() function data have to be an array, edit your .json file to " [] ", 
// now you can add elements.

fs.writeFile("output.json", JSON.stringify(data), 'utf8', function (err) {
    if (err) {
            console.log("An error occured while writing JSON Object to File.");
            return console.log(err);
    }

    console.log("JSON file has been saved.");
});

Upvotes: 1

Ronnie Smith
Ronnie Smith

Reputation: 18565

If you want to add something to an array, you .push it in there.

var arr = [];
arr.push(123);
arr.push({a:1,b:2});
arr.push(null);
arr.push("string");
console.dir(arr);

Upvotes: 0

Related Questions