【发布时间】: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