1

I want to load multiple .json files to an array, but I don't know the exact amount of files.

E.g.:

(in: .../example-folder)

abc.json
xyz.json
uvw.json

array.length == 3

(in .../example_folder)

abc.json 
xyz.json

array.length == 2

How could I do that in javascript? Thanks in advance!

Kind regards,

Soxxes

Edit: Normally I am doing it this way:

function loadJSON(url, callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType('application/json');
    xobj.open('GET', url, true);
    xobj.onreadystatechange = function() {
        if (xobj.readyState == 4 && xobj.status == '200') {
            callback(xobj.responseText);
        }
    };
    xobj.send(null);
}

loadJSON("../example_folder/abc.json", function(res){
    data_parsed = JSON.parse(res);
    data_stringified = JSON.stringify(data_parsed, null, 4);
    abc = data_stringified;
    });
Soxxes
  • 31
  • 1
  • 1
  • 9
  • Check this:https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript/45035939 you can't load json from folder. Are you using nodejs? – Athanasios Kataras Jan 24 '20 at 07:47
  • You can send an AJAX call for each file in the array, just reject 404 responses. Or alternatively send the names of the files with a single AJAX call, and let the server filter the non-existing files, and response with a single object combinating the existing files. – Teemu Jan 24 '20 at 07:55

1 Answers1

1

You can create an API to return a number of JSON files or a list of them. If you don't want to create that API, just put expected response to a specific JSON file.

// api.json
{
  "files": [ "abc.json", "xyz.json" ]
}
Grey Chanel
  • 212
  • 1
  • 5
  • Hey @Grey Chanel, thanks for your answer. Could you be a little bit more precisely, please? :) I edited my post. – Soxxes Jan 24 '20 at 08:17
  • @Soxxes you can call the API or load "api.json" as normal to know number of json files or their locatons, e.g. you know you have "abc.json" and "xyz.json", then load them too. When you add or remove json files, just edit "api.json". Mark this answer as accepted answer if you think it's useful. – Grey Chanel Jan 24 '20 at 11:05
  • You can use jQuery to [load external JSON file](https://codesearchable.com/es/3063643/). – Grey Chanel Jan 25 '20 at 14:05