【问题标题】:How to get value in JSON?如何在 JSON 中获取价值?
【发布时间】:2021-09-02 05:29:59
【问题描述】:

我正在尝试制作一个 Discord 机器人并将应用来自 JSON 文件的命令(例如,如果命令是“abc”,则在命令的数组(列表)中找到“abc”并回复 abc 的数据)。这是我的 JSON 文件中的一个元素(文件很长,因此,没有放完整的文件):

[
    {"howareyou": {
        "Reply": "**Uh, oh... A few minutes ago lost my diamond banana from Middle Ages. But expect this, I'm OK.",
        "NoArguments": true
    }}
]

但问题是:我在这个 JS 代码中收到错误“无法读取未定义的属性“回复””:

const CMDFile = JSON.parse (FS.readFileSync ('./Commands.json', 'utf8', Error_ => { if (Error_) throw Error_ }))

if (Message.content.startsWith ('\\')) { // My prefix is '\'
    if (Used_CMD == '' /* Used CMD is msg content without prefix */ || (Message.mentions.users.first () && Message.mentions.users.first ().id == '123456789012345678')) {
            Cevapla ('Yes, I'm! For more, just use command `\\help`.')
    } else {
        const CMD = CMDFile [Used_CMD],
              Reply = CMD.Reply, NoArg = CMD.NoArguments

顺便说一句,当我使用“\”命令时,我的代码可以正常运行,但是当我输入“\howareyou”时,它会出错TypeError: Cannot read property 'Reply' of undefined。我怎样才能解决这个问题?谢谢。

【问题讨论】:

    标签: javascript node.js json typeerror


    【解决方案1】:

    问题要么是输入文件的格式,要么是从 JSON 获取正确命令的代码。

    1. 或者将您的输入文件更改为:
    {
        "howareyou": {
            "Reply": "**Uh, oh... A few minutes ago lost my diamond banana from Middle Ages. But expect this, I'm OK.",
            "NoArguments": true
        },
        "other_cmd": {
            "Reply": "xx",
            "NoArguments": true
        }
    }
    
    1. 从当前结构中查找命令:
    var CMD = null
    CMDFile.forEach((cmd) => { if(cmd.hasOwnProperty(Used_CMD)) CMD = cmd; });
    

    或(根据评论)

    const CMD = CMDFile.find(cmd => cmd.hasOwnProperty(Used_CMD));
    

    【讨论】:

    • 我认为find 而不是forEach 更适合第二种解决方案
    • 如果我错了,请纠正我,但.forEach(...) 在这里不是有点矫枉过正吗?你就不能let commandData = readJsonData[usedCommandName];吗?
    • 另外,请记住,目前这将为您返回已解析的 object,而不是数组,因此无论如何您都不能使用 findforEach,只是为了清除问题适合同时考虑这两种解决方案的人。
    • @IanH。我已经用“要么/或”澄清了
    猜你喜欢
    • 2021-02-12
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2019-08-02
    • 2021-04-24
    • 2021-12-10
    相关资源
    最近更新 更多