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.
- 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:
- 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 toallQuestions
array. - Now your json data is available in
allQuestions
array and you can access it, for example:
Using .done callback
Remember that$getJSON
runs asynchronously. Such implementation will be not the best idea:
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.