从jQuery / Javascript中的非索引JSON获取单个随机JSON结果

时间:2018-04-14 15:46:19

标签: javascript jquery json

以下是json的格式:

{
  "Hist eb zoso posclifos pit feaxald usow din regichics pi slaxanspeltaxatien": [
    "Paxarrot",
    "Paxarotto"
  ],
  "He dreto zo vech #1 whit sickros axabtol Paxaur VcCaxaltnoupp pi Ronnen": [
    "Vistaxaor Jaxangsen",
    "Vaxax Vaxaltin"
  ],
  "Hist eno eb zoso Jaxapaxanoso axarceheric wrints dis vaxado blem lico, yaxams pi woaxal el flewn sugaxal": [
    "Umosku",
    "Skestu"
  ],
  "Din pit 1581 spoost, JBK axanneuncow whis veen axamfitiens, fut axarse axangnewrodgow hist ethol chlaxatogupp": [
    "Naxavupp SOAR slaxainick",
    "Ismaxankrick zo"
  ]
}

在PHP中这很简单

$json = file_get_contents('test.json');
$json_result = json_decode($json, true);
$randValues = array_intersect_key($json_result, array_flip(array_rand($json_result, 2)));
// this actually brings back 2 random elements
// had to do some more array trimming to unset the first or second

结果:

Array  (
    [He dreto zo vech #1 whit sickros axabtol Paxaur VcCaxaltnoupp pi Ronnen] => Array
    (
        [0] => Vistaxaor Jaxangsen
        [1] => Vaxax Vaxaltin
    )
       )

尝试在jQuery中执行此操作似乎很容易,如果我的json被编入索引并且可以通过length来衡量

我能够在jQuery中加载它的唯一方法(在少数几个不同的变体中)是使用这一行

var json = JSON.parse($.ajax({'url': "test.json", 'async': false}).responseText);

这是console.log(json)的样子:

enter image description here

我发现从json中检索单个随机元素的所有解决方案都是这样的:

var random_entry = json[Math.floor(Math.random() * json.length)]

json格式化的方式只是给了random_entry undefined变量,因为它没有编入索引且没有.length

我意识到如果这个json文件被正确编入索引会更容易获取和解析,但是从json文件中获取没有length的单个随机元素的解决方案是什么?还是index

2 个答案:

答案 0 :(得分:2)

使用Object.keys获取json键的数组并选择一个随机数:

let json = {
  "Hist eb zoso posclifos pit feaxald usow din regichics pi slaxanspeltaxatien": [
    "Paxarrot",
    "Paxarotto"
  ],
  "He dreto zo vech #1 whit sickros axabtol Paxaur VcCaxaltnoupp pi Ronnen": [
    "Vistaxaor Jaxangsen",
    "Vaxax Vaxaltin"
  ],
  "Hist eno eb zoso Jaxapaxanoso axarceheric wrints dis vaxado blem lico, yaxams pi woaxal el flewn sugaxal": [
    "Umosku",
    "Skestu"
  ],
  "Din pit 1581 spoost, JBK axanneuncow whis veen axamfitiens, fut axarse axangnewrodgow hist ethol chlaxatogupp": [
    "Naxavupp SOAR slaxainick",
    "Ismaxankrick zo"
  ]
}

let keys = Object.keys(json)

let random_key = keys[Math.floor(Math.random() * keys.length)]

let result = {};
result[random_key] = json[random_key]

console.log(result)

答案 1 :(得分:0)

您可以使用Object.keys()。它返回一个对象的可枚举键的数组。

var keys = Object.keys(json);
var random = json[keys[Math.floor(Math.random() * keys.length)]];