Dynamically load JSON files based on the quantity of files present

Is there a way to load an unknown number of .json files into an array using JavaScript?

For example:

(in: .../example-folder)

abc.json
xyz.json
uvw.json

array.length == 3

(in .../example_folder)

abc.json 
xyz.json

array.length == 2

If you are unsure about the total number of files, how can this be achieved efficiently in JavaScript?

Thank you for your help!

Best regards,

Soxxes

Edit: Typically, I approach this task like so:

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;
    });

Answer №1

One option is to develop an API that can provide a series of JSON files or even just a list of them. Another solution could be to simply include the expected response within a designated JSON file.

// data.json
{
  "documents": [ "file1.json", "file2.json" ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Default Data Configuration for Mongoose

Exploring the realm of node.js and the MEAN stack, I am venturing into the creation of an application. Within this application, there exists a need for default data in the database. My goal is to ensure that this data is populated automatically upon the ap ...

Cannot chain promises using 'then'

Having trouble understanding why the 'describeDir' promise chain is not working properly. Can anyone help me figure out what I did wrong here? Everything in the code seems to run, but functions like then or finally from the promise API never get ...

The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'. var records = ...

Unable to retrieve data upon page refresh in Next.js

I encountered an issue while trying to develop a basic Next.js page using data fetched from the backend. I am utilizing useSWR for fetching the data. When I refresh the page or load it for the first time after running in development mode, I face a TypeScr ...

Scrolling horizontally with visible vertical overflow is causing the contents of an absolutely positioned div to be hidden

Note: I have thoroughly searched related questions on stackoverflow and this is not a duplicate question. In my code, I have a `div` with `overflow-x: scroll`, but I want the content in the `div` to be visible in the `y` direction. The issue I'm faci ...

Leverage AJAX to fetch data from the database

I've been exploring different methods to automate the process of copying a database table. While replication was suggested as an option, I found it challenging to set up properly. Therefore, I have decided to use a script approach instead. In an effo ...

Adjusting the label on the Formik toggler

I have successfully implemented a switcher using Formik that changes the label accordingly with a boolean value. However, I now need to make the label reflect a string value instead of just "true/false." For example, I want it to display "Text1/Text2" inst ...

Positioning 3D objects in Three.js

I am working on a 3D Scene using Three.js with an Earth shape that currently looks like this: https://i.sstatic.net/zXWki.png My goal is to modify it to resemble something like this: https://i.sstatic.net/w4ypV.jpg The coloring, stars, and texture are ...

Can Unity be used to deserialize a dictionary?

How can I create a dictionary named "dict" with the values {"key": "value"} in Unity using a JSON file like this? { "dict": {"key": "value"} } Below is my class structure: [Serializable] public class MyJson { public Dictionary<string,string> ...

Finding MongoDB data using an Express route and displaying it in a Jade template

Is there a way to retrieve data from MongoDB using an express route and display it in a jade template? Below is the code snippet of my express route (express version 2.5.8): app.get('/showData',function(req,res){ db.collection('comme ...

Requesting data from a database using a GET method

I am aiming to develop a NodeJS application that can serve a JSON array fetched from a database. To implement this, I have incorporated the use of express along with sqlite and sqlite3 packages. Upon executing the code in the terminal, the following output ...

Navigate through the overlay's content by scrolling

Objective: Looking to implement a scroll feature for long content. Issue: Not sure how to create a scroll that allows users to navigate through lengthy content. Thank you! function openNav() { document.getElementById("myNav").style.height = "1 ...

Flutter: Iterating Through JSON Data

I am working on a Json parsing project using Flutter, and the structure of the Json data is as follows: { "Dependents":[ { "Name": "Kim", "Relationship": "Parent", "Entitlements": [ { "GP": { ...

Using Python to extract the audio URL (specifically in mp3 format) from a web player

I have been attempting to extract the URL link from a webpage in order to download the audio as an mp3 file, but so far I have not been successful. Here is the code snippet of the webpage: webpage code Specifically, I am trying to retrieve the value of t ...

Having difficulty updating a web page while utilizing setInterval() and passing a function that utilizes document.write to display JavaScript content on the page

At the core of my issue lies a blank HTML page that incorporates a JavaScript file, with the following code in the JavaScript file: function doIt() { document.writeln("asdf"); } // Alternatively, you can use setTimeout setInterval("doIt()", 5000); Upon ...

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

Accordion elements that are active will move all other content on the page

I am currently working on creating an accordion using the following code: https://codepen.io/rafaelmollad/pen/JjRZbeW. However, I have encountered a problem where when clicking on one of the accordion items, the content expands and pushes the title upward. ...

Unable to show the list of comments with jQuery functionality

Having trouble with my code to display the comment list correctly. I can't seem to get the expected result, could you please review it and help me find the mistake. The current output is as follows: var item = $('<div>'); $.each(d ...

Instructions on sending search fields by pressing the enter key

Developing my application in React.tsx, I have a menu window that consists of numerous div elements with input fields, checkboxes, and select elements. Upon clicking the submit button, a list of results with user-selected filters appears. As an additional ...

Mobile site experiencing slow scrolling speed

The scrolling speed on the mobile version of my website, robertcable.me, seems to be sluggish. Despite conducting thorough research, I have not been able to find a solution. I have attempted to address the issue by removing background-size: cover from my ...