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.

  1. 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.
  2. 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"
             }
         ]
     }
  3. Save json in the same folder as your js script. I named my file questions.json.
  4. Load the json data with $.getJSON. Following example is complete script that loads the questions from json to allQuestions array.
    var allQuestions = new Array();
        
    function loadQuestions() {
        $.getJSON('question.json', function (data) {
            allQuestions = data.quiz;
        }).error(function(){
                console.log('error: json not loaded');
            });
        });
    }
  5. Now your json data is available in allQuestions array and you can access it, for example:
    var currentQuestion = allQuestions[0].question;
    var answerA         = allQuestions[0].a; 
    /* and so on*/

Using .done callback

Remember that$getJSON runs asynchronously. Such implementation will be not the best idea:

loadQuestions();
printQuestion(allQuestions[0]); 
// or do anything else what requires allQuestions already loaded

It’s possible that by the moment of calling printQuestion the JSON will not be loaded yet and the allQuestions size will be 0. To ensure that some operations are done after the JSON is fully loaded, use .done callback.

var allQuestions = new Array();
    
function loadQuestions() {
    $.getJSON('question.json', function (data) {
        allQuestions = data.quiz;
    })
    .error(function() {
        console.log('error: JSON not loaded'); 
    })
    .done(function() {
        console.log( "JSON loaded!" );
        printQuestion(allQuestions[0]); 
    });
}