我如何使用 Javascript 从 JSON 文件中 select 一个随机对象(?)?
How do I select a random object(?) from a JSON file with Javascript?
在我制作的 Discord Bot 中,它需要 select 来自 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
,然后 post 将其嵌入丰富的内容中。我从这里做什么?
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)
您可以select这样的随机名称:
// 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]
// ...
这可以分两步完成
正在使用 Javascript 和本地服务器加载 Json 文件
1> 创建一个 Json 文件,将其命名为 botNames.json,添加您的数据。
注意:.json 文件只能包含 Json 对象、数组或 Json 文字
{
"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')
}
在我制作的 Discord Bot 中,它需要 select 来自 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
,然后 post 将其嵌入丰富的内容中。我从这里做什么?
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)
您可以select这样的随机名称:
// 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]
// ...
这可以分两步完成
正在使用 Javascript 和本地服务器加载 Json 文件
1> 创建一个 Json 文件,将其命名为 botNames.json,添加您的数据。
注意:.json 文件只能包含 Json 对象、数组或 Json 文字
{
"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')
}