如何加载所有json文件数据并将其加载到JavaScript文件中?

时间:2020-03-15 16:16:57

标签: javascript json

你好, 基本上,我想以某种方式加载json文件并获取其数据,然后将其显示在我的js文件中: JSON文件:

{
    "help": "Displays this message"
}

还有我的JS文件

const cmdh = require("../cmdhandle");
const Discord = require("discord.js");
const util = require("../../util");
const json = require("../help.json");

module.exports = {
    aliases: ["?"],
    execute:function(msg, cmd) {
        // Insert code here so that "def" is a list of elements and definitions in the json file
        msg.channel.send(util.genEmbed("Help", def, "#ff5c5c"));
    }
}

2 个答案:

答案 0 :(得分:2)

您已经用const json = require("../help.json")加载了JSON,现在您要做的就是使用json.helpjson["help"]

如果要获取定义和元素的列表,可以使用Object.keysObject.values函数,或者将Object.entries用于键值对。

答案 1 :(得分:0)

const cmdh = require("../cmdhandle");
const Discord = require("discord.js");
const util = require("../../util");
const json = require("../help.json");

module.exports = {
    aliases: ["?"],
    execute:function(msg, cmd) {
        // Get all entires
        Object.entries(json).forEach(([key, msg]) => {
            msg.channel.send(util.genEmbed(key, msg, "#ff5c5c"));
        })
    }
}
相关问题