【问题标题】:Parsing JSON [Node.JS]解析 JSON [Node.JS]
【发布时间】:2017-04-06 23:06:02
【问题描述】:

我正在用 Node.JS 编写一个机器人,我的命令保存在一个 JSON 表中,如下所示:

Commands = {
  "exit": {
    name: "exit",
    desc: "exits the bot",
    usage: "n/a",
    func: function() {
        process.exit(0);
    }
}
}

我想知道如何循环遍历命令表以获取命令的功能/名称等信息,以便我可以实际检查命令是否被说出等。

【问题讨论】:

  • 命令对象是数组吗?

标签: javascript json node.js parsing


【解决方案1】:

如果你有

var Commands = {
  'exit': {
    name: 'exit',
    desc: 'exits the bot',
    usage: 'n/a',
    func: function() {
      process.exit(0);
    }
  }
};

然后类似

var key = "exit";
var name   = Commands[key].name;   <- this should be exit
var result = Commands[key].func(); <- this calls the func

更多错误检查

var ref  = Commands[key];
var name   = ref != null ? ref.name : undefined;
var result = ref != null ? ref.func() : undefined;

【讨论】:

    【解决方案2】:

    你可以试试

      Commands.exit.name
    

    如果 Commands 对象是一个数组,你可以循环它。我做了一个简单的 jsfiddle

    请检查 https://jsfiddle.net/tLLawaxh/

    【讨论】:

      【解决方案3】:

      您可以使用 for in 循环命令对象。

      for (cmd in Commands) {
          //Code to deal with each of the command should go here.
          //cmd contains each of your commands.
          //cmd.name, cmd.usage, cmd.func gives each of the property name
          ....
      }
      

      【讨论】:

      • 好的,我刚刚启动了 Node.JS,但是,如何在 for 循环之外访问 cmd.name 等?
      • 如果您查找任何特定命令,则可以将其分配给某个变量并使用它。
      猜你喜欢
      • 2011-09-23
      • 2015-01-07
      • 2011-05-28
      • 2013-02-15
      • 2020-12-15
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多