Kesava Kesava - 22 days ago 8
JSON Question

Javascript - Extracting data from JSON object (array)

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();'GET', requestURL);
request.responseType = 'json';

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.

Answer Source

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: