Parsing JSON [Node.JS]



我在node.js中写一个bot,我的命令在这样的json表中保存:

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

我想知道如何通过命令表循环以获取命令的函数/名称之类的thig,以便我实际上可以检查命令是否被说出。

您可以使用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
    ....
}

您可以尝试

  Commands.exit.name

如果命令对象是一个数组,您可以循环。我做了一个简单的JSFIDDLE

plz检查https://jsfiddle.net/tllawaxh/

如果您有

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;

最新更新