将JSON文件加载到JavaScript变量中

时间:2015-12-26 03:24:17

标签: javascript jquery json

因此,我需要将以下代码放入JSON文件并将其加载到单独的JavaScript文件中:

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
}];

换句话说,allQuestions的内容需要放在JSON文件中,然后在单独的JavaScript文件中加载到allQuestions变量中。 JSON文件的外观如何?如何将其加载到allQuestions变量中?

3 个答案:

答案 0 :(得分:3)

尝试使用JSON.stringify()$.getJSON()

  

JSON文件的外观如何

"[
  {
    "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
  }
]"
  

如何将其加载到allQuestions变量中?

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

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

答案 1 :(得分:0)

您可以像这样使用ES6 fetch API,

// 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;  
}

以下是使用asyncawait.的方法

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

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

答案 2 :(得分:0)

尝试一下:

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