How to get JSON array from file with getJSON?

前端 未结 2 495
面向向阳花
面向向阳花 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:01

    Your conditional within the for loop prevents anything from being added to your array. Instead, check if your json object has the property, then get the value and add it to your array. In other words:

    if (questions.hasOwnProperty(key)) should be if (json.hasOwnProperty(key))

    Also, you can't simply return the result of an AJAX call like that, because the method runs asynchronously. That return is actually applied to the inner success function callback, not getArray. You have to use a callback pattern in order to pass the data only once it has been received, and operate on it accordingly.

    (Of course since the array is defined in the outer scope you wouldn't have to return it anyway, but if you attempted to use it before the AJAX method ended it would be empty.)

    Assuming you are going to render it to the DOM using a method called 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);
        });
    }
    
    0 讨论(0)
  • 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 };
        });
    });
    
    0 讨论(0)
提交回复
热议问题