繁体   English   中英

将JSON对象中的JSON数组转换为jQuery中的数组

[英]Converting JSON array in JSON object to array in jquery

我正在尝试转换以下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"
            }
        }

    ]
}

通过在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);
});

我收到一个错误未捕获的ReferenceError:未定义sarit

如何获得每个问题的答案值,并在html文件中使用它

sarit的范围是getJSON的成功处理程序,它在外部不存在。

此外,还要考虑到getJSON异步运行,因此根据响应的不同,在调用此方法后立即在内部声明一条语句是错误的。 下一行执行时,ajax调用将不会完成。

document.getElementById("content").innerHTML = JSON.stringify(sarit);时, sarit不存在document.getElementById("content").innerHTML = JSON.stringify(sarit); 被调用,它不在范围内,因此即使尝试使用它也无法看到。

$(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);
    });
});

也就是说,他只会让您["questions"]显示在您的html页面中。 为了获得答案值,您必须遍历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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM