Link to home
Start Free TrialLog in
Avatar of slightlyoff
slightlyoff

asked on

Pull Random records from JSON using Javascript

I'm trying to pull information from a json file.  The goal is to get 9 records returned in random order.
My data looks like this (there are 60 different videos):
{"videos":[
    {"id":"1", "ytID":"ys7Xnw34T5A", "title":"Video 1", "category":"Category 1"},
    {"id":"2", "ytID":"HlrO8gH7AEY", "title":"Video 2", "category":"Category 2"},
    {"id":"3", "ytID":"NzYp5YGK9vc", "title":"Video 3", "category":"Category 3"},
    {"id":"4", "ytID":"brrTb2zmOYd", "title":"Video 4", "category":"Category 4"}
]

Open in new window


I pull the data like this:

$.getJSON(url, function(data){
     //GET THE FIRST VIDEO
     var firstVideo = data.videos[0].title;
     var firstVideoCode = data.videos[0].ytID;
     
     getVideo(firstVideoCode);
     
     var x = 0;
     $.each(data.videos, function(index, videos) {

          if (x < 10){
                //create blockText to display results 
                blockText += '<div class="thumbVids">\
		<a href="#" onclick="getVideo(\'' + videos.ytID + '\')">\
		<img class="vidThumb" src="//i1.ytimg.com/vi/' + videos.ytID + '/hqdefault.jpg" border="0" /></a>\
		<p class="title">' + videos.title + '</p>\
		</div>';
		}
          x++;
       });
});	

Open in new window


I'm not sure the best way to grab a random sampling.  Any suggestions?  Thanks for your help!
ASKER CERTIFIED SOLUTION
Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of slightlyoff
slightlyoff

ASKER

Thank you for your help!  Perfect!