Getting Single Random JSON Result from non-indexed JSON in jQuery/Javascript

Here's how my json is formatted:

{
  "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"
  ]
}

This was simple enough to do in 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

Result:

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

Trying to do this in jQuery seems like it would be easy if my json was indexed and could be measured by length

The only way (out of a handful of different variations) that I was able to get it to load in jQuery was with this single line

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

Here's what my console.log(json) looks like:

enter image description here

All the solutions to retrieve a single random element from json I found were something like this:

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

The way the json is formatted this just gives me a random_entry variable of undefined as it is not indexed and doesn't have a .length.

I realize this would be easier to get and parse if this json file was indexed properly, but what is the solution to get a single random element from a json file that does not have a length or index?

2 answers

  • answered 2018-04-14 15:53 Taki

    use Object.keys to get an array of the json's keys and choose a random one :

    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)

  • answered 2018-04-14 15:54 Teemoh

    You could use Object.keys(). It returns an array of the enumerable keys of an object.

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