簡體   English   中英

將JSON文件加載到JavaScript變量中

[英]Load JSON file into JavaScript variable

因此,我需要將以下代碼放入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變量中?

嘗試使用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

您可以使用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);

試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM