How can jQuery read all the data in the JSON file in a folder?

Asked 2 years ago, Updated 2 years ago, 45 views

For example, if you have some json data in the sample folder and you want to load all of them, how can you describe it?

jquery

2022-09-30 17:51

2 Answers

If you just want to load it, why don't you do the following?

// The file name here is increasing as much as you need.
const filenames = [
  "sample/data.json",
  "sample/data2.json"
];

filenames.forEach(function(filename){
  $.getJSON(filename, function(data){
    console.log (filename, data);
  });
});


2022-09-30 17:51


I've looked it up for the same purpose before and found it wasn't prepared by standard. I have implemented it.

I rewritten the code (TypeScript) that I had in hand to JavaScript.
I don't have an environment right now, so I haven't checked the operation yet (I hope it works well).

The approach is
First, list all the files in the directory, and then narrow them down with extensions.

import fs from 'fs';
import path from 'path';

constenumFilePaths=(dirPath, extension)=>{
    const filePaths=[];

    const funds =fs.readdirSync(dirPath);
    found.each((found)=>{
        const subPath=path.resolve(dirPath, found);
        const stat =fs.statSync(subPath);
        if(stat.isFile()){
            filePaths.push(subPath);
        }
    });

    constfiltered=filePaths.filter((filePath)=>{
        const=path.extname(filePath).toLowerCase().replace('.', '');
        return ext===extension;
    });

    return filtered;
};

const jsonFilePaths=enumFilePaths('./sample', 'json');

Turn this jsonFilePaths in a loop to $.getJSON().

With a few modifications, you can increase the number of extensions you're looking for to more than one. You can also look in a subdirectory.
(Originally, it had that function, but it was omitted when pasting because it was different from your requirements.)


2022-09-30 17:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.