0

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"
    }
]

2 Answers 2

1

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.");
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!! It worked. But I have two problems now, maybe you know a fix? Everytime I try to add a new object it overwrites the previous, so I can only have 1 object on my JSON. I need to have all of them there, I need to ADD objects, not overwrite evertyhing. Also, how can I make so that the objects are inside of an array so I can later on read a random object from the JSON?
0

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

8 Comments

Thank you! But how do I push it from a JavaScript file into a JSON file?
probably var myJson = JSON.parse the file then push it
Sorry, I'm a begginer. How do I make it go to the JSON file? Like a different file. I have an add.js where all of this is happening and then a data.json where I want to store the object
You cannot directly write the files on server using js. As Javascript runs on the client, while the file write to your data.json sits on your server which needs some server-side scripting. You may use node.js express.js server to do that
I'm using node.js!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.