javascriptjsonlocal-files

Load multiple JSON files in pure JavaScript


I am new to JavaScript. I have already understood how to create an object from a JSON-file with JSON.Parse() and now I need to load multiple local JSONs into an array. I've been googling my problem for a while, but everything that I found was related to single JSON files.

Is there any way to do this in pure JavaScript without any libraries like jQuery and etc.?

P.S.: There is no need to work with web-server or else, the code is running locally.


Solution

  • To do this, you need to first get the actual files. Then, you should parse them.

    // we need a function to load files
    // done is a "callback" function
    // so you call it once you're finished and pass whatever you want
    // in this case, we're passing the `responseText` of the XML request
    var loadFile = function (filePath, done) {
        var xhr = new XMLHTTPRequest();
        xhr.onload = function () { return done(this.responseText) }
        xhr.open("GET", filePath, true);
        xhr.send();
    }
    // paths to all of your files
    var myFiles = [ "file1", "file2", "file3" ];
    // where you want to store the data
    var jsonData = [];
    // loop through each file
    myFiles.forEach(function (file, i) {
        // and call loadFile
        // note how a function is passed as the second parameter
        // that's the callback function
        loadFile(file, function (responseText) {
            // we set jsonData[i] to the parse data since the requests
            // will not necessarily come in order
            // so we can't use JSONdata.push(JSON.parse(responseText));
            // if the order doesn't matter, you can use push
            jsonData[i] = JSON.parse(responseText);
            // or you could choose not to store it in an array.
            // whatever you decide to do with it, it is available as
            // responseText within this scope (unparsed!)
        }
    })
    

    If you can't make an XML Request, you can also use a file reader object:

    var loadLocalFile = function (filePath, done) {
        var fr = new FileReader();
        fr.onload = function () { return done(this.result); }
        fr.readAsText(filePath);
    }