Reputation: 33
First things first, I'm a beginner in using Javascript and JSON. I've tried to find an existing answer on Stack Overflow that helps but most of the explanations go over my head (way over my head)! So, I hope someone can help.
I have a JSON file with book information as shown below. The actual file has information for about 5000 books.
[
{
"Book": "The Phenomenon",
"Author": "Bob Bryant",
"Author_link": "abc"
},
{
"Book": "Supreme Commander of Idiots",
"Author": "Cynthia C",
"Author_link": "def"
},
{
"Book": "An Interesting Life",
"Author": "Doris Dodd",
"Author_link": "ghi"
}
]
Considering the array numbers (0 to 4xxx) as book numbers, I want to generate a random number (less than 5000), and then use JavaScript to pull information about that book from the JSON file. Ideally, I want to assign the book name, the author name and the author link to three different variables that I can later use in my user-facing page.
I've tried creating a var, and using JSON.parse to pull specific data from the array, but it is not working. I also saw an example that asked me to use something like this...
var requestURL = 'filename.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
But then, I have no idea how this is working (not that it is working). I'd appreciate any guidance on how to solve this issue.
Upvotes: 3
Views: 2779
Reputation: 265
First, you would grab the data from the local JSON file in whatever way your project requires. Once you have the actual file referenced, parse it as valid JSON.
var jsonData = JSON.parse(jsonFile);
Then you can operate on it as a valid JavaScript object. So, to get a random book from the object, just do as follows:
var randomBook = jsonData[Math.floor(Math.random()*(max-min+1)+min)];
(For an explanation of the random number generation, see this answer.)
That would get a random book between min
and max
from the JSON object. You can grab any info from it by doing:
randomBook.Book
randomBook.Author
randomBook.Author_link
Upvotes: 1
Reputation: 2477
To get the json response, you'll need to add a callback listener. Note that you could also add this as a reference to an existing function.
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
var json = request.responseText;
// do stuff with the json
}
}
To generate a random number between zero and n, use Math.random() * n
, where n is the maximum.
var n = json.length;
var random = Math.floor((Math.random() * n);
To reference an item in your json
data, you can use array and dictionary references.
var randomBook = json[random];
var bookTitle = randomBook.Book
var bookAuthor = randomBook.Author
var bookAuthorLink = randomBook.Author_link
Upvotes: 1