【问题标题】:Why is nothing happening when I push something into a JSON array?为什么当我将某些东西推入 JSON 数组时什么都没有发生?
【发布时间】:2020-07-08 11:12:18
【问题描述】:

我一直在尝试将值推送到 JSON 数组中,但什么都没有发生。没有错误,没有输出,什么都没有。我通过在线查看尝试了无数解决方案,但都没有奏效。这是我的 Javascript 代码:

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

这是我的 JSON 文件:

[
    {"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!"}
]

谢谢!

【问题讨论】:

  • 这是à文件,à文件不能从à脚本修改,这将是一个很大的安全问题
  • @codeanjero 你确定这不是后端 javascript,nodejs 吗?
  • 你是对的对不起,但你仍然必须使用除了 push 之外的其他方式:fs.writeFileSync(filename, JSON.stringify(content));来源:stackoverflow.com/questions/10685998/…
  • 当你说什么都没发生时,它确实发生了。一个新元素被添加到数组中。如果您调试/console.log 数组,您会看到这一点。你的意思是它没有被写回文件吗?因为这不会自动发生。
  • 没有 JSON 数组这样的东西。 JSON 是一种文本格式。在这种情况下,requireing 您的 JSON 文件会解析 JSON 并返回一个数组,该数组是 JSON 文件中数据的副本。您可以随心所欲地操作该数组的副本,但文件不会更改。

标签: javascript json discord.js


【解决方案1】:

试试下面的代码 sn-p 看看是否有效

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

运行上述代码 sn-p 与其余逻辑隔离。 dataset 的值应该是 test

【讨论】:

  • 谢谢!我厌倦了它并理解了我的问题。感谢所有评论的人。我现在真的觉得自己很傻。有点过了我的头。再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 2017-02-16
  • 2012-07-02
  • 1970-01-01
相关资源
最近更新 更多