【问题标题】:JavaScript parsing nested JSON dataJavaScript 解析嵌套的 JSON 数据
【发布时间】:2021-05-06 13:02:36
【问题描述】:

我正在创建一个不和谐机器人(使用 discord.js) 我正在使用嵌入页面编写帮助命令,我的页面工作正常 - 但是,当尝试从 JSON 获取数据时,问题似乎出现了。 我在一个较大的配置文件中设置了 JSON 文件,因此它嵌套在其中。 每个命令都附有它的名称

{
    "other-json-data": "other data",

    "commands": {
        "rule": {
            "info": "This command gives the rules",
            "expectedArgs": "<number>"
        },
        "invite": {
            "info": "Invite new users",
            "expectedArgs": "<no-args>"
        },
        "flip": {
            "info": "Flip a coin",
            "expectedArgs": "<no-args>"
        }
    },

    "other-json-data": "other data"
}

我需要从commands 区域获取每个页面的数据。 我只有一个整数输入(来自页码),但我不知道如何从需要显示的任何命令中获取数据。

对于我项目中的其他内容,我使用它从 JSON 对象 config.commands[arguments].expectedArgs 中获取 expectedArgs,其中配置只是对 JSON 文件的引用,这非常好。参数是一个字符串输入(即rule),它返回来自该命令的任何信息。

但是,有没有办法让第二个说下来(invite)。我试过config.commands[pageNumber].expectedArgs},但是,这似乎不起作用。 pageNumber 将是一个整数,所以它会得到任何值,然后我可以获取expectedArgs

【问题讨论】:

    标签: javascript json discord.js


    【解决方案1】:

    您可以从一个对象中获取所有键并使用它们的索引选择一个。

    const json = {
      "other-json-data": "other data",
      "commands": {
        "rule": {
          "info": "This command gives the rules",
          "expectedArgs": "<number>"
        },
        "invite": {
          "info": "Invite new users",
          "expectedArgs": "<no-args>"
        },
        "flip": {
          "info": "Flip a coin",
          "expectedArgs": "<no-args>"
        }
      },
      "other-json-data": "other data"
    }
    const pageNumber = 1
    // key will be a command name, e.g. 'invite'
    const key = Object.keys(json.commands)[pageNumber]
    const { expectedArgs } = json.commands[key]
    
    console.log(`${key} expects ${expectedArgs}`)

    记住索引范围从零开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2020-01-19
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多