0

I've been trying to push values into a JSON array but nothing has been happening. No error, no output, nothing. I've tried countless solutions by looking online but none of them worked. Here is my Javascript code:

const discord = require('discord.js');
const fs = require('fs');
const dataset = require('./data.json');

module.exports.run = async(client, message, args) => {
    let blocks = args.join(' ').split('&');
    let keyword = blocks[0];
    let response = blocks[1];

    var object = {
        Keyword: keyword,
        Response: response
    };

    dataset.push(object);
};

module.exports.help = {
    name: 'aiadd'
};

Here is my JSON file:

[
    {"Keyword":"hello","Response":"Hey there!"},
    {"Keyword":"hey","Response":"Hiya!"},
    {"Keyword":"hi","Response":"Hello!"},
    {"Keyword":"hiya","Response":"Hi there buddy!"},
    {"Keyword":"sup","Response":"Nothing much, just being a bot! What's up with you?"},
    {"Keyword":"what's up","Response":"The sky lol."},
    {"Keyword":"what is up","Response":"Not much really. I'm just vibing!"},
    {"Keyword":"bye","Response":"See ya later!"}
]

Thanks!

Shaqni
  • 67
  • 1
  • 7
  • It's à file and à file can not be modified from à script, it would be a big security issue – codeanjero Mar 27 '20 at 17:00
  • 1
    @codeanjero are you sure this isnt backend javascript, nodejs? – Jamiec Mar 27 '20 at 17:01
  • 1
    you are right sorry but still you'de have to use other means than push : fs.writeFileSync(filename, JSON.stringify(content)); source :https://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js – codeanjero Mar 27 '20 at 17:03
  • 3
    When you say nothing happens, it does. A new element gets added to the array. You'll see this if you debug/`console.log` the array. Do you mean its not being written back to the file? Because that doesn't happen automagically. – Jamiec Mar 27 '20 at 17:04
  • 1
    There is no such thing as a JSON Array. JSON is a text format. In this case `require`ing your JSON file parses the JSON and returns an array, which is a copy of the data in the JSON file. You can manipulate that copy of the array all you want, but the file will not change. – Heretic Monkey Mar 27 '20 at 17:05

1 Answers1

1

Try the following code snippet and see if it works

const dataset = require('./data.json');
dataset.push("test");
console.log(dataset);

Run the above code snippet in isolation from rest of the logic. The dataset should have the value test

Faraaz Malak
  • 329
  • 1
  • 6
  • Thanks! I tired it and understood my issue. Thanks to everyone else who commented. I feel really stupid now. Kind of went over my head. Thanks again for the help! – Shaqni Mar 27 '20 at 17:19