如何从文件中获取JSON数组的getJSON? [英] How to get JSON array from file with getJSON?

查看:221
本文介绍了如何从文件中获取JSON数组的getJSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能得到一个JSON文件的数组使用Javascript和jQuery

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

我的下一个code triyng,它不工作:

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

这就是所谓的JSON文件:questions.json

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"
        }
    }
}
}

我希望得到这种格式的数组{生物学:{类别:{细胞:{问题1 ....}}}}

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

推荐答案

$。的getJSON 是一个异步函数,因此返回该函数内部的东西什么都不做,因为它不是在范围上,还是没有收到。你应该这样做:

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

这篇关于如何从文件中获取JSON数组的getJSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆