简体   繁体   中英

Read multiple json files into an array of objects in JavaScript

I have multiple json files under a folder that I need to read. The data file path is like:

./data/json1.json
./data/json2.json

My initializer class works as below:

const j1 = require('./data/json1.json');
const j2 = require('./data/json2.json');
init(){
    return j1.concat(j2);
}

Is there a better way to do this as the list of files under data could increase and every time this would require modifications?

I would preferably avoid a solution with looping in the folder and read file to append in an array object in init() .

As a variant:

'use strict';

const fs = require('fs');
const path = require('path');

const dir = './data';

function init() {
  return fs.readdirSync(dir)
           .filter(name => path.extname(name) === '.json')
           .map(name => require(path.join(dir, name)));
}

You can use glob package.

const glob = require("glob");
const path = require("path");

glob('data/*.json', function (er, files) {
  files.forEach(function(file) {
    //Do your thing
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM