Search code examples
jqueryjsonfunctionreturn

jquery function return json value in array


I would make a jquery function that import a json value and return an array when we call it. I coded the following function but the returned array is empty.

The json file is very basic like this example :

{
"fruit": [ "babana", "pineapple", "apple" ],
"vegetable" :  [ "salad", "carrot", "tomato" ]
}

I call my json with the following function

$( function() {
var fruit = new Array();
var vegetable = new Array();
var food = new Array();

function loadJson(result) {
    $.getJSON('myfile.json', function (data) {
        fruit = data.fruit;
        vegetable = data.vegetable;
    })
    .error(function() {
        console.log('error: JSON not loaded');
    })
    .done(function() {
        //console.log( "JSON loaded!" );
        var food = fruit.concat(vegetable);
        return result;
    });
}

After I call this function in another function with

loadJson(food);   loadJson(fruit);

Can you help me?


Solution

  • I think this is what you're looking for, I've fired mine on document ready just so I could test the function quickly, but you should give you the result you're after.

    Answer Updated:

    function loadJson( type ) {
    
    var final_result = null;
        $.ajax({
            type: 'GET',
            url: "test.json",
            async: false,
            dataType: "json",
            success: function (data) {
                var fruit = data['fruit'],
                    vegetable = data['vegetable'],
                    food = fruit.concat(vegetable),
                    result = food;
    
                switch( type ) {
                    case 'fruit':
                        result = fruit;
                        break;
                    case 'vegetable':
                        result = vegetable;
                        break;
                    case 'food':
                        result = food;
                        break;
                }
                final_result = result;
            }
        });
        return final_result;
    }
    
    
    $( document ).ready(function() {
        loadJson( 'food' );
        loadJson( 'fruit' );
        loadJson( 'vegetable' );
    
        var test = loadJson( 'fruit' );
        console.log( test );
     });