如何使用Javascript从JSON文件中选择随机对象(?)?

时间:2018-04-06 03:29:09

标签: javascript node.js discord discord.js

在我正在制作的Discord Bot中,它需要从JSON文件中选择一个随机对象。我目前的代码是:



    function spawn(){
        if (randomNum === 24) return
        const name = names.randomNum
        const embed = new Discord.RichEmbed()
        .setTitle(`${name} has been found!`)
        .setColor(0x00AE86)
        .setThumbnail(`attachment://./sprites/${randomNum}.png`)
        .setTimestamp()
        .addField("Quick! Capture it with `>capture`!")
        msg.channel.send({embed});
    }




JSON文件如下所示:



{
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud",
    ...
}




我希望它随机选择其中一个,例如303,并将其发布在丰富的嵌入中。我该怎么办?

3 个答案:

答案 0 :(得分:2)

const jsonData = {
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud",
}
const values = Object.values(jsonData)

const randomValue = values[parseInt(Math.random() * values.length)]

console.log(randomValue)

答案 1 :(得分:2)

您可以选择这样的随机名称:

// Create array of object keys, ["311", "310", ...]
const keys = Object.keys(names)

// Generate random index based on number of keys
const randIndex = Math.floor(Math.random() * keys.length)

// Select a key from the array of keys using the random index
const randKey = keys[randIndex]

// Use the key to get the corresponding name from the "names" object
const name = names[randKey]

// ...

答案 2 :(得分:0)

这可以分两步完成

使用Javascript和本地服务器加载Json文件

1>创建一个Json文件,将其命名为 botNames.json ,添加您的数据。

注意:.json文件只能包含Json Object,Array或Json literal

{
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud"
}

使用XMLHttpRequest()加载数据,您可以使用以下函数加载.json文件,传递回调函数并将路径作为参数。

function loadJSON(callback,url) {   
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', url, true); 
  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

要生成随机索引,您可以使用以下表达式

Math.floor(lowerLimt +(upperLimit - lowerLimit + 1)* Math.Random())

这将为您提供 [lowerLimit,upperLimit]

范围内的值

注意:这是可能的,因为 Math.random()会生成 [0,1)

您的回拨功能将

function callback1(response){
        var botNames = JSON.parse(response)
        var keys = Object.keys(botNames);
        var randomProperty = keys[Math.floor(keys.length*Math.random())]
        var botName = botNames[randomProperty]
        console.log(botName);
    }

您可以在代码中使用上述概念



function loadJSON(callback,url) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', url, true); 
    xobj.onreadystatechange = function () {
            if (xobj.readyState == 4 && xobj.status == "200") {
            // sending the resonse to your callback
            callback(xobj.responseText);
            }
    };
    xobj.send(null);
}

function spawn(){
        loadJSON(function(response){
          //This is your callback function

          var names = JSON.parse(response)
          var keys = Object.keys(botNames);
          var randomNum = keys[Math.floor(keys.length*Math.random())]
            
          if (randomNum === 24) return
          const name = names[randomNum]
          const embed = new Discord.RichEmbed()
          .setTitle(`${name} has been found!`)
          .setColor(0x00AE86)
          .setThumbnail(`attachment://./sprites/${randomNum}.png`)
          .setTimestamp()
          .addField("Quick! Capture it with `>capture`!")
          msg.channel.send({embed});
        },'/PATH_TO_YOUR_JSON/botNames.json')
    }