3

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.

Kesava
  • 33
  • 5
  • Does your JSON file really look like that? A JSON file has to start with { and end with }. – hardfork Sep 25 '17 at 20:39
  • look at resources for loading JSON from file system. https://nodejs.org/api/fs.html once you have it in memory it is simple. `var book = books[Math.floor((Math.random() * books.length) ]` – Koborl Sep 25 '17 at 20:41
  • 1
    @Koborl I don't think OP is using Node to be able to use `fs`. – TheOdd Sep 25 '17 at 20:42
  • 1
    Unless the JSON file is created on the fly, just add `var books = ` at the start and include it in your HTML. No request or parsing necessary. That way you can access the array data using `books[i].Author` and so on. –  Sep 25 '17 at 20:44
  • @Alpha You're right! I didn't even notice that my JSON file was incorrectly formatted. Any idea how I can correct it? Replacing the [] with {} doesn't seem to work. – Kesava Sep 25 '17 at 20:56
  • @Kesava Your JSON file seems fine to me. – TheOdd Sep 25 '17 at 21:04
  • Thanks @OwenHines. I now have 2 versions of my JSON file. One that starts and ends with [ and ], and the other one uses { and }. The problem right now seems to be loading the JSON file using Javascript. Chrome does not allow XMLHttpRequest requests for local files. – Kesava Sep 25 '17 at 22:16
  • 1
    @Kesava I assume you've seen [this](https://stackoverflow.com/a/5034547/6836963) answer about JSON validity? – TheOdd Sep 25 '17 at 23:54

2 Answers2

1

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
the_storyteller
  • 2,335
  • 1
  • 26
  • 37
  • I'm trying to load a local JSON file but Chrome says "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." – Kesava Sep 26 '17 at 05:17
1

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
TheOdd
  • 265
  • 1
  • 16
  • "grab the data from the local JSON file" How do I do this? I tried XMLHttpRequest but Chrome says 'no' to accessing local files. – Kesava Sep 26 '17 at 05:16
  • Used some ideas from [link](https://gist.github.com/thiagodebastos/08ea551b97892d585f17) to access JSON data. It works now. Thanks a lot for helping out. – Kesava Sep 26 '17 at 06:42