0

I need to read and parse JSON data using JavaScript. I can do this using jQuery, inside of an HTML page. For the languages JSON content

{ "json":
    { "languages" :
        [
            {"language":
                {
                    "text":"Deutsch",
                    "id":"ce4bb97b-8a8f-40c1-b4d7-34ebc8872ccd",
                    "code":"de"
                }
            },
            {"language":
                {
                    "text":"English",
                    "id":"1aaafaae-8dff-4055-9736-3970c9f6844b",
                    "code":"en"
                }
            }
        ]
    }
}

I use this JavaScript to get the ID for the first language:

$.getJSON("languages.json", function(data, status) {
    var obj = JSON.parse(JSON.stringify(data));
    $("#languages").html(obj.json.languages[0].language.id);
}).done(function() {
    console.log("done success");
}).fail(function() {
    console.log("fail error");
}).always(function() {
    console.log("always complete");
});

But I would reuse this mechanism for more JSON contents, soomething like this:

(function($) {
    $(document).ready(function() {
        var language_id = getLanguages()[0];
    });
})(jQuery);

function getLanguages() {
    var obj = JSON.parse(JSON.stringify(getJsonData("languages.json")));
    return obj.json.languages;
} 

function getJsonData(file) {
    return $.getJSON(file, function(data, status) {
        ...
    });
} 

What is the best practice?

  • You can't return anything from an async function. `obj` in your example would be a reference to the `jqXHR` object returned from `$.getJSON()`, not the data received from the request. To fix this use callback or promises - see the duplicate for more information on working with this pattern – Rory McCrossan Feb 05 '19 at 13:47
  • Well it is npt possible to return with an asynchronous call so not going to happen the way you tried – epascarello Feb 05 '19 at 13:47
  • `var obj = JSON.parse(JSON.stringify(getJsonData("languages.json")));` will not work because your `getJsonData()` function returns a `Promise` object, not the actual data. The data is only accessible once the callback supplied to $.getJSON has been executed...this is because the request is asynchronous. – ADyson Feb 05 '19 at 13:48
  • If you want to re-use the data outside the callback, then either a) in the callback, assign the result to a global variable (or at least a variable with high enough scope to be useful to you)...but that has its own downsides in terms of integrity of your code design, or b) you do what your getJsonData() is doing and return a `Promise`...then any code which actually needs the data can call the function, get the Promise, put its own "done" callback on the end of it, and then use the data once the callback has run. A Promise can have as many "done" callbacks attached as you wish. – ADyson Feb 05 '19 at 13:49
  • The duplicate question now being shown above has a more comprehensive explanation in the answers, I suggest you study the examples. – ADyson Feb 05 '19 at 13:50

0 Answers0