Search code examples
javascriptarraystableau-apigetjson

Javascript .getJSON multiple URLs


I have WEbDataconnector in Javascript, which download data from .json file and load table:

myConnector.getData = function(table, doneCallback) {

        $.getJSON("http://url/api/opls/number/tasks?apiKey", function(resp) {        
            var feat = resp.data,
                tableData = [];

            // Iterate over the JSON object
            var keys = Object.keys(feat);
            for (var i = 0, len = keys.length; i < len; i++) {
                tableData.push({
                    "taskId": feat[keys[i]].taskId,
                    "owner": feat[keys[i]].owner,
                    "description": feat[keys[i]].description,
                    "responsible": feat[keys[i]].responsible,                     

                });
            }

            table.appendRows(tableData);
            doneCallback();
        });

My problem is that i have multiple URL, with different numbers and apikeys. And i need combine data from all URLs into one table. Could anyone please help me out? Thank you.

edit:

If i add more elements to data.push() method it ends with:"null is not an object" because some objects in JSON are null,

example of JSON:

"1026533": {
        "taskId": 1026533,
        "opl": 6919,
        "owner": "name",
        "description": "text",
        "responsible": "name",  
        "taskStart": {
            "date": "2016-03-21 13:28:11.000000",
            "timezone_type": 3,
            "timezone": "Europe\/Prague"

but sometimes there is an element taskStart with null:

"1026535": {
        "taskId": 1026535,
        "opl": 6919,
        "owner": "name",
        "description": "text",
        "responsible": "name",
        "taskStart": null,

how can i check this and push all data or null? thank you


Solution

  • Use recursion and named function expression with a list of URL.

    myConnector.getData = function (table, doneCallback) {
        var urls = [ /* the urls */]
        if (urls.length == 0) return doneCallback();
        $.getJSON(urls.shift(), function callback(resp) {
            var feat = resp.data,
                tableData = [];
            // Iterate over the JSON object
            var keys = Object.keys(feat);
            for (var i = 0, len = keys.length; i < len; i++) {
                tableData.push({
                    "taskId": feat[keys[i]].taskId,
                    "owner": feat[keys[i]].owner,
                    "description": feat[keys[i]].description,
                    "responsible": feat[keys[i]].responsible,
    
                });
            }
            table.appendRows(tableData);
            var url = urls.shift();
            if (url) return $.getJSON(url, callback); // recursion happens here 
            doneCallback();
        });
    }