CSE 154

Section 5: Using JSON with JavaScript

JSON

Building a trivia game with JSON

We’ll build this:

Exercise 1: Fetch Trivia

First step: let’s download a JSON file with a bunch of trivia questions!

Start with this HTML skeleton (there is no CSS).

JSON Format

Our HTTP response will look like this:

{
  "trivia": [
    {
     "question": "What's a cat?",
     "answer": "An animal!",
     "difficulty": 3
    },
    {
      "question": "What's a dog?",
      "answer": "An even better animal!",
      "difficulty": 1
    },
    ...
  ]
}
              

Fetchin’

We can GET these from the following URL:

https://courses.cs.washington.edu
/courses/cse154/17au/sections/sect06/code/qa.json

Fetch the JSON and store it in a module-global variable. Use DevTools or console.log to make sure this works.

Exercise 2: Add Questions

Fill the #q-output div with a random question from the JSON result when "New Question" is pressed.

Choose a random element from a list like so:

function randomChoice(choices) {
  let index = Math.floor(Math.random() * choices.length);
  return choices[index];
}

Note that the buttons on the page are initially disabed. You should enable them when the JSON data from Part I is successfully stored.

Exercise 3: Reveal Answers

Now, let’s fill in the corresponding answer when "Show Answer" is pressed.

You may want to think about storing the just-shown question in a module-global variable.

Exercise 4: Indicate Difficulty

Show, next to the question, the difficulty.

In the JSON resource, 1 corresponds to Easy, 2 to Medium, and 3 to Hard.

Exercise 4: Solution

There is a working solution here.

Don't peek at the JavaScript before you’ve finished!

Extra Exercise

Use a public Trivia API!

There is a trivia API you may use at opentdb.com.

This API uses almost the same syntax for a JSON response as you just used for our 7-question JSON, but has much more additional questions and information in the JSON. For example, the url https://opentdb.com/api.php?amount=50 will return 50 random trivia questions with information about the question type, category, etc.

Update your solution from the earlier slides to use this API instead of the one we gave you, and replace the "trivia" JSON attribute with "results" and "answer" to "correct_answer".

When looking over the response JSON, it will be pretty messy since there is so much information and the API doesn't format the JSON output as we do. You may find it useful to copy/paste the JSON with this JSON "pretty print" tool and compare with the JSON output you used in Part I.

Extra Exercise Solution

Solution code here

Working solution here