[英]Converting JSON array in JSON object to array in jquery
I'm trying to convert the following json: 我正在尝试转换以下json:
{
"questions": [
{
"question#1": "How much is 3+1",
"correct answer": 1,
"answers": {
"ans#1": "5",
"ans#2": "4",
"ans#3": "3"
}
},
{
"question#5": "How much is 2+4",
"correct answer": 0,
"answers": {
"ans#1": "6",
"ans#2": "4",
"ans#3": "7",
"ans#4": "5"
}
}
]
}
by using the following code in Jquery: 通过在Jquery中使用以下代码:
$(document).ready(function(){
$.getJSON("data.json", function(json) {
console.log(json); // this will show the info it in firebug console
var sarit = Object.keys(json); // "a"
});
/*var update = document.getElementById("content");
update.innerHTML("test");*/
document.getElementById("content").innerHTML = JSON.stringify(sarit);
});
I got an error-Uncaught ReferenceError: sarit is not defined 我收到一个错误未捕获的ReferenceError:未定义sarit
How can I get the answers' value of each question, and use it in the html file, aka content 如何获得每个问题的答案值,并在html文件中使用它
The scope of sarit
is the succeed handler for getJSON
, it doesn't exist outside. sarit
的范围是getJSON
的成功处理程序,它在外部不存在。
Also, take into account that getJSON
runs async so having a statement inmediatly after a call to this method depending on the response is wrong. 此外,还要考虑到
getJSON
异步运行,因此根据响应的不同,在调用此方法后立即在内部声明一条语句是错误的。 The the ajax call won't be finished by the time next line is executed. 下一行执行时,ajax调用将不会完成。
sarit
doesn't exist when document.getElementById("content").innerHTML = JSON.stringify(sarit);
当
document.getElementById("content").innerHTML = JSON.stringify(sarit);
时, sarit
不存在document.getElementById("content").innerHTML = JSON.stringify(sarit);
is called and it isn't in the scope so couldn't be seen even if it was try this instead. 被调用,它不在范围内,因此即使尝试使用它也无法看到。
$(document).ready(function(){
$.getJSON("data.json", function(json) {
console.log(json); // this will show the info it in firebug console
var sarit = Object.keys(json); // "a"
document.getElementById("content").innerHTML = JSON.stringify(sarit);
});
});
That said his will only get you ["questions"]
displayed in your html page. 也就是说,他只会让您
["questions"]
显示在您的html页面中。 In order to get the answers value you have to traverse the json to retrieve the values like so: 为了获得答案值,您必须遍历json来检索值,如下所示:
$(document).ready(function(){
$.getJSON("data.json", function(json) {
var anserFor1st = json.questions[0].answers;
var anserFor2nd = json.questions[1].answers;//If it's more than two use a loop
document.getElementById("content").innerHTML = JSON.stringify(anserFor1st) + "<br/>" + JSON.stringify(anserFor2nd);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.