1

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?

4
  • Never ever use async:false. It is a terrible practice and is deprecated. The warning in browser console regarding that issue is telling you not to use it Commented Apr 14, 2018 at 15:55
  • The way the json is formatted using async: false was the only way I found so far to be able to return it into a variable.. Removing it returns a console error of Uncaught SyntaxError: Unexpected token u in JSON at position 0 Commented Apr 14, 2018 at 16:01
  • You need to learn to work with asynchronous requests. Thoroughly study: How do I return the response from an asynchronous call?. The answer is a very good tutorial. Again that warning is telling you it might break soon Commented Apr 14, 2018 at 16:04
  • I do yes :) Okay thank you for the link. Commented Apr 14, 2018 at 16:05

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

This is only bringing back a single value from the json tree, though. In the code snippet, the result Paxarotto I am looking to return it as a single array element { "Hist eb zoso posclifos pit feaxald usow din regichics pi slaxanspeltaxatien": [ "Paxarrot", "Paxarotto" ] }
i edited the snippet to return an object like the one in your comment.
I see, perfect! Had not seen a reference anywhere to doing this method to return a single unique value, thank you.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.