How to load external .json to array in js

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(){
            $.getJSON('questions.json',function(data){
                allQuestions = data.quiz;
                console.log('json loaded successfully');
            }).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*/
    

This solution can be developed further with encoding and decoding json.