Julian
Julian

Reputation: 97

Load JSON file into JavaScript variable

So, I need to put the following code into a JSON file and load it into a separate JavaScript file:

var allQuestions = [{
  question: "What is Elvis Presley's middle name?",
  choices: ["David", "Aaron", "Eric", "Jack"],
  correctAnswer: 1
}, {
  question: "Who is the singer of the Counting Crows?",
  choices: ["Adam Duritz", "John Adams", "Eric Johnson", "Jack Black"],
  correctAnswer: 0
}, {
  question: "Who is the Queen of Soul?",
  choices: ["Mariah Carey", "Whitney Houston", "Aretha Franklin", "Beyonce"],
  correctAnswer: 2
}, {
  question: "Which famous group was once known as The Quarrymen?",
  choices: ["The Beatles", "The Birds", "The Who", "Led Zeppelin"],
  correctAnswer: 0
}];

In other words, the contents of allQuestions need to go in a JSON file and then loaded into the allQuestions variable in a separate JavaScript file. What would the JSON file look like and how would I load it into the allQuestions variable?

Upvotes: 4

Views: 11666

Answers (3)

I_Al-thamary
I_Al-thamary

Reputation: 3993

Try this:

var myList;
$.getJSON('JsonData.json')
.done(function (data) {
myList = data;
});

Upvotes: 0

Mystical
Mystical

Reputation: 2783

You can use the ES6 fetch API, like so:

// return JSON data from any file path (asynchronous)
function getJSON(path) {
    return fetch(path).then(response => response.json());
}

// load JSON data; then proceed
getJSON('/path/to/json').then(data => {
    // assign allQuestions with data
    allQuestions = data;  
}

Here is how to do it using async and await.

async function getJSON(path, callback) {
    return callback(await fetch(path).then(r => r.json()));
}

getJSON('/path/to/json', data => allQuestions = data);

Upvotes: 1

guest271314
guest271314

Reputation: 1

Try using JSON.stringify() , $.getJSON()

What would the JSON file look like

"[
  {
    "question": "What is Elvis Presley's middle name?",
    "choices": [
      "David",
      "Aaron",
      "Eric",
      "Jack"
    ],
    "correctAnswer": 1
  },
  {
    "question": "Who is the singer of the Counting Crows?",
    "choices": [
      "Adam Duritz",
      "John Adams",
      "Eric Johnson",
      "Jack Black"
    ],
    "correctAnswer": 0
  },
  {
    "question": "Who is the Queen of Soul?",
    "choices": [
      "Mariah Carey",
      "Whitney Houston",
      "Aretha Franklin",
      "Beyonce"
    ],
    "correctAnswer": 2
  },
  {
    "question": "Which famous group was once known as The Quarrymen?",
    "choices": [
      "The Beatles",
      "The Birds",
      "The Who",
      "Led Zeppelin"
    ],
    "correctAnswer": 0
  }
]"

how would I load it into the allQuestions variable?

$.getJSON("/path/to/json", function(data) {
  var allQuestions = data;
})

jsfiddle https://jsfiddle.net/dydhgh65/1

Upvotes: 3

Related Questions