6

如何使用 javascript 和 jquery 获取 json 文件的数组 json

我正在尝试使用下一个代码,但它不起作用:

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

这是名为的 json 文件: 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"
        }
    }
}
}

我想得到一个具有这种格式的数组 {Biology:{Category:{cell:{question1....}}}}

4

2 回答 2

9

$.getJSON是一个异步函数,因此在该函数中返回一些东西什么都不做,因为它不在范围内,或者尚未接收。您可能应该执行以下操作:

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 };
    });
});
于 2013-02-17T01:15:01.843 回答
3

循环中的条件for可防止将任何内容添加到数组中。相反,检查您的 json 对象是否具有该属性,然后获取该值并将其添加到您的数组中。换句话说:

if (questions.hasOwnProperty(key))应该if (json.hasOwnProperty(key))

此外,您不能简单地return得到这样的 AJAX 调用的结果,因为该方法是异步运行的。这return实际上应用于内部success函数回调,而不是getArray. 您必须使用回调模式才能仅在收到数据后才传递数据,并相应地对其进行操作。

(当然,由于数组是在外部范围内定义的,因此您无论如何都不必返回它,但如果您在 AJAX 方法结束之前尝试使用它,它将为空。)

假设您要使用名为的方法将其渲染到 DOM renderJSON

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
                });
            }
        }
        renderJSON(questions);
    });
}
于 2013-02-17T01:00:23.263 回答