Building a trivia game with JSON
We’ll build this:
First step: let’s download a JSON file with a bunch of trivia questions!
Start with this HTML skeleton (there is no CSS).
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
},
...
]
}
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.
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.
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.
Show, next to the question, the difficulty.
In the JSON resource, 1
corresponds to Easy, 2
to Medium, and
3
to Hard.
There is a working solution here.
Don't peek at the JavaScript before you’ve finished!
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.
Solution code here
Working solution here