During my work on the javascript Qt quiz, I had to decide how to store quiz questions. I have chosen the external json file for that purpose. This post describes this solution.
- Write json content with the use of json parser to avoid typos. Parsers like http://json.parser.online.fr/ will help you to painfully create even the longest json files — you will see error immediately when you break the syntax.
- The valid json can look like this:
{ "quiz": [ { "question": "Question 1", "a": "Answer a", "b": "Answer b", "c": "Answer c", "correct": "a" }, { "question": "Question 2", "a": "Answer a", "b": "Answer b", "c": "Answer c", "correct": "b" }, { "question": "Question 3", "a": "Answer a", "b": "Answer b", "c": "Answer c", "correct": "c" } ] } - Save json in the same folder as your js script. I named my file
questions.json. - Load the json data with
$.getJSON. Following example is complete script that loads the questions from json toallQuestionsarray.var allQuestions = new Array(); $(function(){ $.getJSON('questions.json',function(data){ allQuestions = data.quiz; console.log('json loaded successfully'); }).error(function(){ console.log('error: json not loaded'); }); }); - Now your json data is available in
allQuestionsarray and you can access it, for example:var currentQuestion = allQuestions[0].question; var answerA = allQuestions[0].a; /* and so on*/
This solution can be developed further with encoding and decoding json.
