gpt4 book ai didi

javascript - 将 JSON 文件加载到 JavaScript 变量中

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:58:17 26 4
gpt4 key购买 nike

因此,我需要将以下代码放入一个 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()

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

关于javascript - 将 JSON 文件加载到 JavaScript 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34468233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com