Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

javascript - How to get JSON array from file with getJSON?

How could I get an array json of a json file with javascript and jquery

I was triyng with the next code, with it doesnt work:

var questions = [];
function getArray(){
    $.getJSON('questions.json', function (json) {
        for (var key in json) {
            if (json.hasOwnProperty(key)) {
                var item = json[key];
                questions.push({
                    Category: item.Category
                });
            }
        }
        return questions;
    })
}

this is the json file called: questions.json

{
"Biology":{
    "Category":{
        "cell":{
            "question1":{
                "que1":"What is the cell?"
            },
            "option1":{
                "op1":"The cell is the basic structural and functional unit",
                "op2":"is a fictional supervillain in Dragon Ball"
            },
            "answer1":"opt1"
        }
    }
},
"Astronomy":{
    "Category":{
        "Mars":{
            "question1":{
                "que1":"How many moons does Mars?"
            },
            "option1":{
                "op1":"5",
                "op2":"2"
            },
            "answer1":"opt2"
        }
    }
}
}

I want to get an array with this format {Biology:{Category:{cell:{question1....}}}}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$.getJSON is an asynchronous function, so returning something inside that function does nothing, as it's not in scope, or received yet. You should probably do something like:

function getArray(){
    return $.getJSON('questions.json');
}

getArray().done(function(json) {
    // now you can use json
    var questions = [];
    $.each(json, function(key, val) {
        questions[key] = { Category: val.Category };
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...