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

时间:2021-09-25 09:21:43

In my Discord Bot that I am making, it needs to select a random object from a JSON file. My current code is this:

在我正在构建的不和谐机器人中,它需要从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});
    }

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. What do I do from here?

我想让它随机选择其中的一个,比如303,然后将它嵌入到一个丰富的嵌入中。我该怎么做呢?

3 个解决方案

#1


1  

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]

// ...

#2


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)

#3


0  

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.

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

Note: .json files can only contain Json Object, Array or Json literal

注意:.json文件只能包含Json对象、数组或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()加载数据,可以使用below函数加载传递回调函数和路径作为参数的.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())

数学。下限(最小值+(上限-下限+1)*Math.Random())

this will give you values in the range [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')
    }

#1


1  

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]

// ...

#2


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)

#3


0  

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.

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

Note: .json files can only contain Json Object, Array or Json literal

注意:.json文件只能包含Json对象、数组或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()加载数据,可以使用below函数加载传递回调函数和路径作为参数的.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())

数学。下限(最小值+(上限-下限+1)*Math.Random())

this will give you values in the range [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')
    }