How to get JSON array from file with getJSON?

前端 未结 2 498
面向向阳花
面向向阳花 2020-12-18 04:53

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 = [];
fun         


        
2条回答
  •  半阙折子戏
    2020-12-18 05:20

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

提交回复
热议问题