简体   繁体   English

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

[英]How do I select a random object(?) from a JSON file with Javascript?

In my Discord Bot that I am making, it needs to select a random object from a JSON file. 在我正在制作的Discord Bot中,它需要从JSON文件中选择一个随机对象。 My current code is this: 我当前的代码是这样的:

  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}); } 

The JSON file looks like this: JSON文件如下所示:

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

I want it to pick a random one of those, such as 303 , and post it in a rich embed. 我希望它随机选择其中之一,例如303 ,并将其张贴在丰富的嵌入物中。 What do I do from here? 我从这里做什么?

 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) 

You can select a random name like this: 您可以选择一个随机名称,如下所示:

// 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]

// ...

This can be done in two steps 这可以分两步完成

Loading Json file using Javascript and local server 使用Javascript和本地服务器加载Json文件

1> Create a Json file, name it botNames.json , add your data. 1>创建一个Json文件,将其命名为botNames.json ,添加您的数据。

Note: .json files can only contain Json Object, Array or Json literal 注意:.json文件只能包含Json Object,Array或Json文字

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

Use XMLHttpRequest() to load the data, you can use below function to load the .json file passing a callback function and the path as an argument. 使用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);
}

To generate a random index you can use the below expression 要生成随机索引,可以使用以下表达式

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

this will give you values in the range [lowerLimit,upperLimit) 这将为您提供[lowerLimit,upperLimit)范围内的

Note: This is possible because Math.random() generates a fractional number in the range [0,1) 注意:这是可能的,因为Math.random()生成范围为[0,1)的小数

Your callback function will be 您的回调函数将是

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);
    }

You can use above concepts in your code as 您可以在代码中使用上述概念作为

 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') } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM