简体   繁体   中英

Converting JSON array in JSON object to array in jquery

I'm trying to convert the following 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:

$(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

How can I get the answers' value of each question, and use it in the html file, aka content

The scope of sarit is the succeed handler for getJSON , it doesn't exist outside.

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. The the ajax call won't be finished by the time next line is executed.

sarit doesn't exist when 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. In order to get the answers value you have to traverse the json to retrieve the values like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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