首页 > 解决方案 > 使用 Javascript 读取本地 JSON [Discord 机器人]

问题描述

我想提取我的 .json 文件的数据,并按给定的名称在不和谐通道过滤中显示它。在这种情况下,msg变量包含我要搜索的名称。

var msg;
if (message.content.startsWith(prefix + prefix)) {
    msg = message.content;
    message.channel.send(msg.substring(2)); //this is just for testing
}

现在有了这个名字,我不知道如何在我的 .json 文件中搜索并提取数据。这是我的 .json 文件的一部分

{
  "ID": "1",
  "Nombre": "luffy caca",
  "Tipo": "str",
  "Clase principal": "fighter"
},
{
  "ID": "2",
  "Nombre": "luffy manco",
  "Tipo": "int",
  "Clase principal": "slasher"
},
{
  "ID": "3",
  "Nombre": "luffy g2",
  "Tipo": "str",
  "Clase principal": "driven",
  "Clase secundaria": "slasher"
}

因此,当我在msg变量上获得名称“luffy g2”时,我想提取“ID:3”的数据。

标签: javascriptjsonbotsdiscord

解决方案


尝试这个:

var msg =[
    {
      "ID": "1",
      "Nombre": "luffy caca",
      "Tipo": "str",
      "Clase principal": "fighter"
    },
    {
      "ID": "2",
      "Nombre": "luffy manco",
      "Tipo": "int",
      "Clase principal": "slasher"
    },
    {
      "ID": "3",
      "Nombre": "luffy g2",
      "Tipo": "str",
      "Clase principal": "driven",
      "Clase secundaria": "slasher"
    }
  ];
  
  var idToFind = msg.find(x => x.Nombre == "luffy g2").ID;
  
  console.log(idToFind);

find方法将:

数组中满足提供的测试功能的第一个元素的值。否则返回未定义。


推荐阅读